4xx 时 StatusCodeResult 未记录到 App Insights

StatusCodeResult not Logged to App Insights when 4xx

在我的 ASP.NET 核心 3.1 web api 中,我使用 ControllerBase 中的 ObjectResult StatusCode([ActionResultStatusCode] int statusCode, [ActionResultObjectValue] object value) 方法来 return 某些类型的错误和 422 状态代码。在以前的 ASP.NET 版本中,抛出带有状态代码信息的异常是标准的,记录器会拾取它,因为它是一个实际的异常。现在我有这样的代码

public async Task<IActionResult> RequestSomething(RequestObject request)
{
  if(request.id == 0)
  {
    return StatusCode(422, "ID cannot be blank.");
  }
}

我期待在应用洞察中看到与此相关的内容,但什么也没有。理想情况下我也会收到消息,但至少错误日志将是一个好的开始!我有请求、异常、依赖项调用都显示出来,所以我知道它已连接并正在工作。

我不想到处注入记录器并在每个记录器之前添加记录行。 return以这种方式编辑时,如何设置 Application Insights 以捕获所有 422 状态代码结果?

你完全正确。您不需要在所有 Controllers/ 方法中注入 Logger。您只需执行以下操作即可。

  1. 安装 Nuget 包(Microsoft.ApplicationInsights.AspNetCore
  2. 在启动的 ConfigureServices 方法中添加 services.AddApplicationInsightsTelemetry();
  3. Link App Service 和 Application Insights(我想你已经完成了)。

下面是它在 App Insights 中的样子。

我在 ActionMethod 中的代码与您的类似。

[HttpGet]
        public IActionResult Get()
        {
                return StatusCode(422, "ID cannot be blank or 1.");
        }

对于 App Insights 的新手,您可以在 https://praveenkumarsreeram.com/2020/07/11/6-steps-to-integrate-application-insights-with-net-core-application-hosted-in-azure-app-service/

了解如何将 App Insights 与 App Service 集成