Application Insights and failed request response codes
Although Application Insights doesn't record this as a 500, but rather a 200. Successful request is false, but the response code is still wrong.
As far as I know, if application has no error handling middleware Application Insights will report response status code 200 when unhandled exception is thrown. We could find detailed info from this article. I am using the following code in the method Configure and I could get the correct response status code.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (!Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.DisableTelemetry)
{
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
}
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseIISPlatformHandler();
app.UseExceptionHandler(options => {
options.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "text/html";
var ex = context.Features.Get<IExceptionHandlerFeature>();
if (ex != null)
{
var err = $"<h1>Error: {ex.Error.Message}</h1>{ex.Error.StackTrace }";
await context.Response.WriteAsync(err).ConfigureAwait(false);
}
});
});
app.UseStaticFiles();
app.UseMvc();
}
Related videos on Youtube
Dave New
Updated on July 17, 2022Comments
-
Dave New almost 2 years
When an exception is unhandled in our web API, a response code 500 (Internal Server Error) will return to the client.
Although Application Insights doesn't record this as a 500, but rather a 200.
Successful request
isfalse
, but the response code is still wrong.How can I get the corrrect response codes in my telemetry?
Startup's
Configure
:public void Configure(IApplicationBuilder app, IHostingEnvironment environment) { if (!TelemetryConfiguration.Active.DisableTelemetry) { // Add Application Insights to the beginning of the request pipeline to track HTTP request telemetry. app.UseApplicationInsightsRequestTelemetry(); // Add Application Insights exceptions handling to the request pipeline. Should be // configured after all error handling middleware in the request pipeline. app.UseApplicationInsightsExceptionTelemetry(); } app.UseRequireHttps(environment.IsLocal()); app.UseMiddleware<NoCacheMiddleware>(); app.UseJwtBearerAuthentication(...); app.UseCors("CorsPolicy"); app.UseStaticFiles(); app.UseCompression(); app.UseMvc(); }