Overview Of Filters In MVC

In MVC applications, Controllers have action methods, and action method performs the operation when any user interacts with the user interface. Suppose, when the user clicks on any button, then the corresponding action method gets executed but this action method does not get executed directly. It has to be passed in several steps. That means, it follows the route - when user clicks on button, the request is routed to find the Controller and the corresponding action method is called.

If we want to perform any operation before or after the action method is called, then we have to think about filters because filters are used for performing pre- and post-logic before and after the action method gets executed.

Action filters are the pre- and post processing logic, getting executed just before executing the action methods and after the execution of methods. The use of action filters is for writing the logic which is needed to be executed before an action method. Suppose, sometimes we need to write some security logic or authentication, then we can use action filter. We can do this in action method but this is not good practice, in case of every action method. So, we can write an action filter and enable it either at Controller level, action method level, or globally.

Type of Filters
  1. Authorization filter
  2. Action filter
  3. Result Filter
  4. Exception Filter

Authorization filters are used for security purposes, for example, performing a authorization logic and validation logic. These are the classes which implement IAuthorizationFilter Interface. Authorization filters always get executed before all filters.

These classes implement IActionFilter interface and implement two methods - OnActionExecuting and OnActionExecuted. OnActionExecuting runs before the action method gets executed and OnActionExecuted runs after the action method is executed.

Result Filters are used for applying the logic those need to be executed during the result execution (Action result). It implements the IActionResult and needs to implement the OnResultExecuting and OnResultExecuted methods. OnResultExecuting runs before the ActionResult object is executed and OnResultExecuted runs after the result.

Exception filters execute when any unhandled exceptions occur in the execution of ASP.NET pipeline for creating the log and redirecting to the error page. Exception filters implement the IExeptionFilter interface and it has one method, onException.

Some interfaces which are involved in Action Filter,

  1. IActionFilter
  2. IResultFilter
  3. IExceptionFilter
  4. IAuthorizationFilter

Important interfaces and methods that need to implement in the case of custom filters -

 

Some predefined filters in MVC

  1. Authorize
  2. HandleError
  3. OutputCache
  4. RequireHttps
  • Authorize restricts unauthenticated users or roles to access the action. This is basically AuthorizeAttribute class.
  • HandleError executes when any unhandled exception occurs inside the Controller Action Methods.
  • OutputCache is used for storing the action results into cache, for a time period.
  • RequireHttps forces unsecured HTTP requests to be resent over HTTPS.

How to create custom action filter

The custom action filters can be easily created by a class that is inherited by the ActionFilterAttribute class. This ActionFilterAttribute class is implemented by two interfaces - IActionFilter and IActionResult. So, we can override one of the methods in custom action filter. The ActionFilterAttribute class has four methods,

  1. OnActionExecuting
  2. OnActionExecuted
  3. OnResultExecuting
  4. OnResultExecuted

I have already explained about these four methods earlier, in this article. We can override any of these methods into our custom action filter class to implement the business logic.

Now, I am writing a class, MyCustomActionFilter, which is inherited by ActionFilterAttribute class and overrides all four methods for setting some ViewBag value into it.

Note

ActionFilterAttribute class comes into System.Web.Mvc namespace. Please have a look.

 

Our custom action filter is ready, and now, we need to use it into our action or on Controller but in this example, I am using it only in the Index Action method. For calling the action filter, we only need to simply decorate it on the action method or Controller by the class name inside the square bracket. Please see the given snapshot.

The code for Index View.

 

The output screen is shown below.

 

It is clearly visible that we did not assign any ViewBag value into the index method. We did it into our custom action filter and when our Index Action is executed, then we get the output with three ViewBag values. The fourth one is not visible on screen and that was assigned into OnResultExecuted method.

The OnResultExecuted executes at last on action method execution. This event will be executed after content is rendered to the View, so that time, content was rendering to the View and OnResultExecuted event could not be executed.

Different ways to use Action filters

  1. Action level
  2. Controller Level
  3. Global Filter

Action Level

In the above example, I used this approach. I decorated our custom action filter only on Index Method .This filter will not apply on other action methods.

Controller Level

Sometimes, we want to write a logic that should execute in each action method of a Controller. Then, we decorate our Controller with the Custom Action Filter.
 

Global Filter

Sometimes, we want to write a logic that should execute for all action methods in an application. Then, we will register it as global filter. For registering it, we have to go in FilterConfig.cs file inside the App_Start folder, and register into RegisterGlobalFilters method (please see the image).

Up Next
    Ebook Download
    View all
    Learn
    View all