Search code examples
c#exceptionasp.net-mvc-5global-asaxapplication-error

MVC global exceptions


I am coding an MVC 5 internet application, and I have a question in regards to handling exceptions globally.

I have my Application_Error setup in my global.asax file. This caters to errors such as 404 HttpExceptions.

How can I send all errors that occur in a controller to the Application_Error function? An example is the following exception:

System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (name="").

I have written a OnException(ExceptionContext filterContext) for my controller, but am not sure on how to get the Application_Error function to handle these errors. Do I need to pass the exception from the OnException function, or is this the wrong approach?

Thanks in advance.


Solution

  • You can create a global filter by adding the following class to your App_Start folder:-

    public class FilterConfig
        {
            public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            {
                filters.Add(new HandleErrorAttribute());
    
            }
        }
    

    HandleErrorAttribute can be replaced with your own custom Exception Filter.

    All you then need to do is make sure you add the following line of code to the App_Start method of your Gloabal.asax :-

     public class MvcApplication : System.Web.HttpApplication
        {
            protected void Application_Start()
            {
                //AreaRegistration.RegisterAllAreas();
                //RouteConfig.RegisterRoutes(RouteTable.Routes);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            }
        }
    

    Hope this helps.