w3resource

ASP.NET MVC- Filters


In an MVC application, a controller routes a user request using the appropriate methods. But situations may arise when some logics or checks needs to be done on a request before its being routed. ASP.NET MVC provides us with filters for such situations.

ASP.NET MVC Filter are custom classes where we can write custom logic to execute before or after an action method executes.

In an ASP.NET MVC application, filter can be used in two approaches: Declarative or Programmatic approach. Declarative approach entails applying a filter attribute to an action method or controller class and programmatic involves implementing a corresponding interface.

ASP.NET MVC provides different types of filters by default. The following table outlines filter types, built-in filters for the type and interface which must be implemented to use these custom filter classes.

Filter Typeh Descriptionh Built-in Filter Interfaceh
Authorization filters Performs authentication and authorizes before executing action method. [Authorize], [RequireHttps] IAuthorizationFilter
Action filters Performs some operation before and after an action method executes.   IActionFilter
Result filters Performs some operation before or after the execution of view result. [OutputCache] IResultFilter
Exception filters Performs some operation if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline. [HandleError] IExceptionFilter

To better understand how filter works in detail, let's take a look at the built-in Exception filter.

An exception filter executes when there is an unhandled exception occurs in your application. HandleErrorAttribute ([HandlerError]) class is a built-in exception filter class in MVC framework. This built-in HandleErrorAttribute class renders Error.cshtml included in the Shared folder by default, when an unhandled exception occurs.

ASP.NET MVC- Filters

The following example demonstrates built-in exception filter HandErrorAttribute.

//Example: Authorization Filter
[HandleError]
public class ActivitiesController: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();
    }        
}

In the above example, we have applied [HandleError] attribute to ActivitiesController. So, the Error page will be displayed if any action method of ActivitiesController throw an unhandled exception. Note that unhandled exception is an exception which is not caught by a try-catch block.

Filters when applied to the controller will automatically be applicable to all the action methods in that controller, while those applied to a method will be specific to that method.

Ensure the CustomError mode in System.web section of the web.config is "on" for HandleErrorAttribute to work properly.

Example of SetCustomError Configuration in web.config

<customErrors mode="On" />

Now, if you we should run the application, and navigate to the localhost:51152/Activities/Index, we would get an error page because we throw exception in Index action method for illustration purposes.

Thus, HandleError attribute will display common error page for any unhandled exception occurred in ActivitesController.

In the next tutorial, we will look at filter registration and other use cases of these filters in an MVC application.



Inviting useful, relevant, well-written and unique guest posts