MVC4 Custom HandleErrorAttribute,未调用global.asax中的方法

Kma*_*man 6 asp.net-mvc asp.net-mvc-4

我无法在我的MVC4应用程序中使用Custom 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);
    }
  }
Run Code Online (Sandbox Code Playgroud)

在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???");
    }

  }
Run Code Online (Sandbox Code Playgroud)

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

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

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

<customErrors mode="On">
</customErrors>
Run Code Online (Sandbox Code Playgroud)

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

hai*_*770 11

RegisterGlobalFilters在你的内部创建了方法Global.asax,但是从MVC 4开始,全局过滤器注册在一个单独的文件中指定App_Start/FilterConfig.cs.

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

在指定文件中添加自定义筛选器注册,或手动调用(本地)RegisterGlobalFiltersin Application_Start.