Tutorialsteacher

Follow Us

ASP.NET MVC- Filters

In ASP.NET MVC, a user request is routed to the appropriate controller and action method. However, there may be circumstances where you want to execute some logic before or after an action method executes. ASP.NET MVC provides filters for this purpose.

ASP.NET MVC Filter is a custom class where you can write custom logic to execute before or after an action method executes. Filters can be applied to an action method or controller in a declarative or programmatic way. Declarative means by applying a filter attribute to an action method or controller class and programmatic means by implementing a corresponding interface.

MVC provides different types of filters. The following table list filter types, built-in filters, and interface that must be implemented to create custom filters.

Filter TypeDescriptionBuilt-in FilterInterface
Authorization filtersPerforms authentication and authorizes before executing an action method.[Authorize], [RequireHttps]IAuthorizationFilter
Action filtersPerforms some operation before and after an action method executes.

 

IActionFilter
Result filtersPerforms some operation before or after the execution of the view.[OutputCache]IResultFilter
Exception filtersPerforms some operation if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline.[HandleError]IExceptionFilter

To understand the filter in detail, let's take an example of a built-in Exception filter. Exception filter executes when an unhandled exception occurs in your application. The HandleErrorAttribute class is a built-in exception filter class that renders the Error.cshtml by default when an unhandled exception occurs.

Error.cshtml

The following example demonstrates the use of [HandError] attribute on the controller class.

Example: Exception Filter
[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        //throw exception for demo
        throw new Exception("This is unhandled exception");
            
        return View();
    }

    public ActionResult About()
    {
        return View();
    }

    public ActionResult Contact()
    {
        return View();
    }        
}

Above, the [HandleError] attribute applied to the HomeController. So, an error page Error.cshtml will be displayed if any action method of the HomeController throws an unhandled exception. Please note that unhandled exceptions are exceptions that are not handled by the try-catch blocks.

Filters applied to the controller will automatically be applied to all the action methods of a controller.

Please make sure that the CustomError mode is on in System.web section of web.config.

Example: Set CustomError Mode in web.config
<customErrors mode="On" />

Now, if you run the application, you would get the following error page because we throw an exception in the Index() action method for the demo purpose.

HandleError demo

Register Filters

Filters can be applied at three levels.

Global Level Filters

You can apply filters at a global level in the Application_Start event of the global.asax.cs file by using default FilterConfig.RegisterGlobalFilters() method. The global filters will be applied to all the controller and action methods of an application.

The [HandleError] filter is applied globally in the MVC application by default in every MVC application created using Visual Studio, as shown below.

Example: Register Global Filters
// MvcApplication class contains in Global.asax.cs file 
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    }
}

// FilterConfig.cs located in App_Start folder 
public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }
}

Controller Level Filters

Filters can also be applied to the controller class. Controller level filters are applied to all the action methods. The following filter are applicable to all the action methods of the HomeController, but not on other controllers.

Example: Action Filters on Controller
[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult About()
    {
        return View();
    }

    public ActionResult Contact()
    {
        return View();
    }

}

Action Method Filters

One or more filters can also applied to an individual action method. The following filter applied only on the Index() action method.

Example: Filters on Action Method
public class HomeController : Controller
{
    [HandleError]
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult About()
    {
        return View();
    }

    public ActionResult Contact()
    {
        return View();
    }

}

Learn how to create a custom filters.