The ASP.NET MVC framework supports four different types of filters:
- Authorization filters – Implements the
IAuthorizationFilterattribute. - Action filters – Implements the
IActionFilterattribute. - Result filters – Implements the
IResultFilterattribute. - Exception filters – Implements the
IExceptionFilterattribute.
System.Web.Mvc.FilterAttribute class.To create a class that inherits from the base Filter class and implements one or more of the
IAuthorizationFilter, IActionFilter, IResultFilter, or ExceptionFilter interfaces gives implementation for particular required filter. Filters are executed in the order listed above. For example,
authorization filters are always executed before action filters and
exception filters are always executed after every other type of filter.Authorization filters are used to implement authentication and authorization for controller actions. For example, the Authorize filter is an example of an Authorization filter.
Action filters contain logic that is executed before and after a controller action executes. You can use an action filter, for instance, to modify the view data that a controller action returns.
Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.
Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors.
Customize order of execution: Each different type of filter is executed in a particular order. If you want to control the order in which filters of the same type are executed then you can set a filter's Order property.
e.g. base
ActionFilterAttribute class has following methods: - OnActionExecuting – This method is called before a controller action is executed.
- OnActionExecuted – This method is called after a controller action is executed.
- OnResultExecuting – This method is called before a controller action result is executed.
- OnResultExecuted – This method is called after a controller action result is executed.