IActionFilter转500为BadRequest后,Application Insights日志失效问题
解决方案:返回400同时保留Application Insights异常日志
你猜的没错,ExceptionHandled = true会告诉ASP.NET Core框架该异常已被处理,导致Application Insights默认的异常收集机制跳过了这条异常记录。要实现返回400响应同时保留异常日志,最直接的方式是手动将异常提交到Application Insights。
具体实现步骤
- 在过滤器中注入
TelemetryClient(Application Insights的核心日志客户端) - 处理异常时先调用
TrackException手动记录异常 - 再设置响应结果并标记异常已处理
修改后的过滤器代码:
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
相关产品推荐
相关产品推荐

