MVC4 Custom HandleErrorAttribute, the method in global.asax is not called

I cannot get Custom HandleErrorAttribute to be used in my MVC4 application.

A custom class that raises an exception

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); } } 

In Global.asax, I added a new static method:

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

When an exception is thrown, error.chstml is loaded, but the OnException override in the HandlErrorAttribute user attribute is never called.

I suspect that the RegisterGlobalFilters method in Global.asax is not called, and the exception there exception (see code) confirms this. This exception is never thrown.

In the web.config file, I set customErrors On:

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

I used the same approach in another solution, and I do not understand why this HandleErrorAttribute extension does not work.

+6
source share
1 answer

You created the RegisterGlobalFilters method inside your Global.asax , but since MVC 4 the registration of global filters is specified in a separate file in App_Start/FilterConfig.cs .

The line FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters) in your Global.asax calls the registration defined in the specified file.

Either add your own filter registration to the specified file, or manually call your (local) RegisterGlobalFilters in Application_Start .

+9
source

Source: https://habr.com/ru/post/948634/


All Articles