gpt4 book ai didi

c# - Application Insights 和失败的请求响应代码

转载 作者:行者123 更新时间:2023-11-30 23:18:57 26 4
gpt4 key购买 nike

当我们的 Web API 中未处理异常时,响应代码 500(内部服务器错误)将返回给客户端。

尽管 Application Insights 不会将此记录为 500,而是记录为 200。成功请求false,但响应代码仍然错误。

Application Insights failed request

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

启动的配置:

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

最佳答案

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.

据我所知,如果应用程序没有错误处理中间件,当抛出未处理的异常时,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

关于c# - Application Insights 和失败的请求响应代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40527905/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com