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

如何从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}");
            }
        }
    }
}

补充说明

  1. inherit参数的作用:设为true时会检查方法继承链上的Attribute;如果你的DontLogPathAttribute只直接标记在Action上,设为false性能会略好一些。
  2. 控制器级别的Attribute检查:如果需要判断控制器是否标记了该Attribute,可以同时检查actionDescriptor.ControllerTypeInfo.GetCustomAttribute<DontLogPathAttribute>(inherit: true),再根据业务逻辑组合判断条件。
  3. ASP.NET Core兼容性:如果是在ASP.NET Core中使用(而非传统ASP.NET MVC),HandleErrorAttribute的用法略有差异,但获取ControllerActionDescriptor的逻辑是一致的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:45:25