c# - 从 HandleErrorAttribute 中获取 Action 的属性

标签 c# asp.net-mvc error-handling custom-attributes

我有一个位于 Controller 顶部的自定义错误属性:

public class JsonExceptionAttribute : HandleErrorAttribute
    {
        private ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        public override void OnException(ExceptionContext errorContext)
        {
            if (errorContext.ExceptionHandled) return;
            if (!errorContext.Action.Attributes.ContainsType(typeof(DontLogPathAttribute)) {    // THIS IS PSEUDOCODE
              _log.Error($"Oopsie. {HttpContext.Current.Request.Path}");
            }

        }
    }

在我的 Controller 顶部,我只需添加我的属性:

[JsonException]
public class UserController {
  public ActionResult JustAnAction{}

  [DontLogPath]
  public ActionResult SelfService(string myHash, int userId) {}
}

我通常会记录 Api 调用的路径,以防出现错误。但有一些操作我不想这样做。这些情况具有 DontLogPathAttribute (这只是一个空的属性类)

在 ExceptionHandling (OnException) 中,我想查明此属性是否存在。但在ExceptionContext中我什至没有找到一个属性来确定当前的Action。

错误日志之前的行是纯伪代码,显示了我想要实现的目标。这可以吗?

(我在 SO 中看到了一些类似的问题,但在这些情况下,它从来都不是必须处理的 ExceptionContext。)

最佳答案

这应该可以完成工作

    public override void OnException(ExceptionContext errorContext)
    {
        string actionName = errorContext.RouteData.Values["action"] as string;

        MethodInfo method = errorContext.Controller.GetType().GetMethods()
            .FirstOrDefault(x => x.DeclaringType == errorContext.Controller.GetType() 
                            && x.Name == actionName);

        IEnumerable<Attribute> attributes = method.GetCustomAttributes();

        //DoStuff
    }

关于c# - 从 HandleErrorAttribute 中获取 Action 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48931273/

相关文章:

c# - Awesomnium 帖子参数

asp.net-mvc - DropDownListFor 未设置选定值

c# - Visual Studio 2010 Express C# 限制

jquery - 视频流显示在 Microsoft Edge 中不起作用

asp.net-mvc-3 - MVC3的奇怪行为

error-handling - 如何处理无效 zlib 字节的 Dart 异常

php - SoapClient 管理错误/异常

c# - 在 .net 核心 Web api 和 Angular 6 中启用 CORS

C# System.NullReferenceException 错误谷歌日历

c# - 如何为整个 USB 驱动器制作校验和?