Filters in MVC

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. 


Types of Filters

ASP.NET MVC framework provides five types of filters.
  1. Authentication filters - Authentication filter runs before any other filter or action method. Authentication confirms that you are a valid or invalid user. Action filters implements the IAuthenticationFilter interface. 
  2. Authorization filters - These are responsible for checking User Access.These filters used to implement authentication and authorization for controller actions.
  3. Action filters - Action Filter is an attribute that you can apply to a controller action or an entire controller. This filter will be called before and after the action starts executing and after the action has executed.
  4. Result filters - These filters contains logic that is executed before and after a view result is executed. 
  5. Exception filters - These filters can be used as an exception filter to handle errors raised by either your controller actions or controller action results.

Following diagram shows how these filters interact in filter pipeline during request and response life cycle.