使用 DeveloperExceptionPage 时如何使用 ApplicationInsights 2.x 记录 ASP.NET Core 应用程序中的异常

Lie*_*ero 2 .net azure azure-application-insights asp.net-core

是否有有关 ApplicationInsights 2.x 和 asp.net core 的任何文档?

我发现了这个: https: //learn.microsoft.com/en-us/azure/application-insights/app-insights-asp-net-exceptions,但看起来已经过时了。

它使用“HandleErrorAttribute”,但它是.NET Framework 的类,而不是.net core。

Amo*_*mor 5

在 ASP.NET Core 中,您可以通过实现 IExceptionFilter 接口来处理异常。下面的代码供您参考。

public class GlobalExceptionFilter : Microsoft.AspNetCore.Mvc.Filters.IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        var telemetry = new TelemetryClient();
        var properties = new Dictionary<string, string> { { "custom-property1", "property1-value" } };
        telemetry.TrackException(context.Exception, properties);
    }
}
Run Code Online (Sandbox Code Playgroud)

定义过滤器后,您可以在ConfigureServices方法中添加MVC服务时注册它。

services.AddMvc().AddMvcOptions(opt=> { opt.Filters.Add(new GlobalExceptionFilter()); });
Run Code Online (Sandbox Code Playgroud)