应用程序见解和失败的请求响应代码

时间:2016-11-10 12:41:21

标签: c# azure asp.net-core azure-web-sites azure-application-insights

如果在我们的网络API中未处理异常,则响应代码500(内部服务器错误)将返回客户端。

尽管Application Insights并未将其记录为500,而是200. Successful requestfalse,但响应代码仍然存在错误。

Application Insights failed request

如何在遥测中获得正确的响应代码?

初创公司的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();
}

2 个答案:

答案 0 :(得分:2)

  

虽然Application Insights不会将其记录为500,而是200.成功的请求是错误的,但响应代码仍然是错误的。

据我所知,如果应用程序没有错误处理中间件,则在抛出未处理的异常时,Application Insights将报告响应状态代码200。我们可以从this article找到详细信息。我在方法配置中使用以下代码,我可以获得正确的响应状态代码。

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();
}

enter image description here

答案 1 :(得分:0)

ApplicationInsights跟踪交互,但在客户端将错误记录为自定义事件或服务器添加中间件代码的情况下(根据@ fei-han),不会报告错误

如果要使用Analytics(分析)警报,那么我使用的Azure Data Lake查询是:

let sitename = "localhost:26047/api";
requests
| where timestamp > ago(1d)
| where url contains sitename
| where resultCode contains "40" 
| order by timestamp desc 

要获得警报,您可以通过Google Analytics(分析)刀片创建新的“规则”,费用约为每月1.50美元。