如何从HandleErrorAttribute内部判断Action是否存在DontLogPathAttribute
解决方法:在HandleErrorAttribute的OnException中判断Action是否存在指定Attribute
我懂你的需求——在自定义错误处理Attribute里,想跳过那些标记了DontLogPathAttribute的Action的路径记录,对吧?其实你可以通过ExceptionContext里的ActionDescriptor获取当前Action的元信息,具体操作如下:
核心思路
ExceptionContext.ActionContext.ActionDescriptor包含了当前执行Action的详细描述,我们可以将其转换为ControllerActionDescriptor(针对控制器中的Action),然后通过它的MethodInfo属性检查是否标记了目标Attribute。
代码实现示例
public class CustomErrorAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext exceptionContext) { base.OnException(exceptionContext); // 先确认当前上下文的Action属于控制器Action if (exceptionContext.ActionContext.ActionDescriptor is ControllerActionDescriptor actionDescriptor) { // 检查当前Action方法是否标记了DontLogPathAttribute var dontLogAttribute = actionDescriptor.MethodInfo.GetCustomAttribute<DontLogPathAttribute>(inherit: true); if (dontLogAttribute == null) { // 未标记该Attribute,执行路径记录逻辑 string apiPath = exceptionContext.HttpContext.Request.Path; // 这里写入你的日志记录代码,比如: // Logger.LogInformation($"API调用路径: {apiPath}"); } } } }
补充说明
inherit参数的作用:设为true时会检查方法继承链上的Attribute;如果你的DontLogPathAttribute只直接标记在Action上,设为false性能会略好一些。- 控制器级别的Attribute检查:如果需要判断控制器是否标记了该Attribute,可以同时检查
actionDescriptor.ControllerTypeInfo.GetCustomAttribute<DontLogPathAttribute>(inherit: true),再根据业务逻辑组合判断条件。 - ASP.NET Core兼容性:如果是在ASP.NET Core中使用(而非传统ASP.NET MVC),
HandleErrorAttribute的用法略有差异,但获取ControllerActionDescriptor的逻辑是一致的。
内容的提问来源于stack exchange,提问作者Ole Albers
相关产品推荐
相关产品推荐

