【问题标题】:MVC4 Custom HandleErrorAttribute, method in global.asax not calledMVC4 自定义 HandleErrorAttribute,未调用 global.asax 中的方法
【发布时间】:2013-07-03 14:42:23
【问题描述】:

我无法在我的 MVC4 应用程序中使用自定义 HandleErrorAttribute。

记录异常的自定义类

  public class HandleAndLogErrorAttribute : HandleErrorAttribute
  {
    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

    public override void OnException(ExceptionContext filterContext)
    {
      var message = string.Format("Exception     : {0}\n" +
                                  "InnerException: {1}", 
                                  filterContext.Exception,
                                  filterContext.Exception.InnerException);
      Logger.Error(message);
      base.OnException(filterContext);
    }
  }

在 Global.asax 中,我添加了一个新的静态方法:

  public class MvcApplication : System.Web.HttpApplication
  {
    protected void Application_Start()
    {
      AreaRegistration.RegisterAllAreas();

      WebApiConfig.Register(GlobalConfiguration.Configuration);
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
      RouteConfig.RegisterRoutes(RouteTable.Routes);
    }

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
      filters.Add(new HandleAndLogErrorAttribute()); //Todo: log all errors
      throw new Exception("not called???");
    }

  }

当抛出异常时,会加载 error.chstml,但不会调用自定义 HandlErrorAttribute 中的 OnException 覆盖。

我怀疑 Global.asax 中的 RegisterGlobalFilters 方法没有被调用,并且在那里抛出异常(参见代码)证实了这一点。永远不会抛出该异常。

在 web.config 文件中,我设置了 customErrors On:

<customErrors mode="On">
</customErrors>

我在另一个解决方案中使用了相同的方法,但我不明白为什么这个 HandleErrorAttribute 扩展不起作用。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    您在 Global.asax 中创建了 RegisterGlobalFilters 方法,但由于 MVC 4,全局过滤器注册在 App_Start/FilterConfig.cs 的单独文件中指定。

    Global.asax 中的行 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters) 正在调用指定文件中定义的注册。

    要么在指定文件中添加您的自定义过滤器注册,要么在Application_Start 中手动调用您的(本地)RegisterGlobalFilters

    【讨论】:

    • 这和MVC3有区别吗?因为我相信我在那里成功地使用了相同的方法。谢谢你的回答!
    • 是的,它与 MVC3 不同。它对你有用是有道理的,因为这是注册过滤器的常规方法,通过将它们添加到 Global.asax 本身定义的 public static void RegisterGlobalFilters 中。
    • @haim770,如果您在方法RegisterGlobalFilters 上使用Find references,您将看到它没有被任何代码引用。无论 MVC 版本如何,都会出现这种情况。
    猜你喜欢
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    相关资源
    最近更新 更多