Learn about Filters and its types in MVC



Hi friends, today we are going to learn about MVC filters and its types. In MVC if you want to perform some logic before or after the action execution and this is done by adding MVC attribute or custom attribute which contains the code or logic. You can create your own custom filter by implementing the MVC filter interface or by inheriting the methods of ASP.NET MVC filter attribute class.

Order of Filter execution:
Authentication filter
Authorization filter
Action filter
Result filter
Exception filter

1. Authentication filter
Authentication filter is introduced in MVC 5.This is used to authenticate the valid request. This runs first, before any other filters or the action method. Authentication interface contain OnAuthentication and OnAuthenticationChallenge methods. OnAuthentication runs before OnAuthenticationChallenge method. You can write you own code in custom filter attribute and write your own logic and use that attribute on controller or on controller action.

Create a class CustomAuthenticationFilter and write below code there.

2. Authorization filter
The Authorization filter attribute implements the IAuthorizationFilter interface. This is used to check if user is authorized for the request.  Authorization Runs first, before any other filters or the action method

You can create your custom AuthorizeAttribute.

3. Action Filters
If you want to pre process or post process the action method request then the action filter is used. Action filter is executer before or after action is executed. The IActionFilter interface is used to create an Action Filter which provides two methods OnActionExecuting and OnActionExecuted which will be executed before or after an action is executed.

You can create your custom ActionAttribute.

4. Result Filters
If you want to execute a piece of code before or after generating the result for an action, a result filter is used. The Action Result type can be ViewResult, PartialViewResult, JsonResult, EmptyResult, etc. which derives from the ActionResult class. Result filters are called after the Action filters. The IResultFilter interface is used to create Result Filter which provides two methods, OnResultExecuting and OnResultExecuted.

You can create your custom ResultFilterAttribute.

5. Exception Filters
If you want to execute a piece of code, and when exception occurs during the actions execution or filters execution. Exception filter is used. The IExceptionFilter interface is used to create an Exception Filter which provides OnException method.



Summary: In above example we have learned about MVC filters and how to implement custom MCV filters.


Please enter your comment!
Please enter your name here