You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IActionFilter转500为BadRequest后,Application Insights日志失效问题

解决方案:返回400同时保留Application Insights异常日志

你猜的没错,ExceptionHandled = true会告诉ASP.NET Core框架该异常已被处理,导致Application Insights默认的异常收集机制跳过了这条异常记录。要实现返回400响应同时保留异常日志,最直接的方式是手动将异常提交到Application Insights。

具体实现步骤

  1. 在过滤器中注入TelemetryClient(Application Insights的核心日志客户端)
  2. 处理异常时先调用TrackException手动记录异常
  3. 再设置响应结果并标记异常已处理

修改后的过滤器代码:

public class InternalServerErrorFilter : IActionFilter, IOrderedFilter
{
    private readonly TelemetryClient _telemetryClient;

    // 构造函数注入TelemetryClient
    public InternalServerErrorFilter(TelemetryClient telemetryClient)
    {
        _telemetryClient = telemetryClient;
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        if (context.Exception == null)
        {
            return;
        }

        // 手动将异常发送到Application Insights
        _telemetryClient.TrackException(context.Exception);

        context.Result = new BadRequestResult();
        context.ExceptionHandled = true;
    }

    public int Order => int.MaxValue - 10;
}

注意事项

  • 确保项目已正确配置Application Insights:Program.cs中需包含builder.Services.AddApplicationInsightsTelemetry();(默认模板一般会自动添加)
  • TelemetryClient会自动携带请求ID、用户信息等上下文,和框架默认日志收集的效果一致

内容的提问来源于stack exchange,提问作者isxpjm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 02:52:34