Action Filter in ASP.NET MVC Applications
Posted On: 10-Jan-2016 09:20
In this article we will try to see what are action filters, how we can use it and how we can create own custom action filters in an ASP.NET MVC application. Action filters are attributes that you can put on Action or entire controller. Action filters are an excellent way of injecting extra processing logic into the MVC pipeline. We will try to understand action filters and how to create custom action filter.
What are Action Filters
Action filters are attributes that you can put on Action or entire controller. Action filters modify the way in which Action executing. MVC provides different inbuilt Action Filter as
- OutputCache – caches the output of a controller action for a specified amount of time.
- HandleError – handles errors raised when a controller action executes.
- Authorize – enables you to restrict access to a particular user or role.
You can also create you own Action Filter. For suppose you want to create custom authentication system or log the user activity or going to modify the response content (minify the response contents) etc. In all cases you can create you custom Action Filter.
How to create Custom Action Filter
For create a new custom Filter you need to know different type of Action Filters:
- Authentication filters - Implements the IAuthenticationFilter attribute.
- Authorization filters – Implements the IAuthorizationFilter attribute.
- Action filters – Implements the IActionFilter attribute.
- Result filters – Implements the IResultFilter attribute.
- Exception filters – Implements the IExceptionFilter attribute.
Filters are executed in the order listed above.The base class of action filters is the System.Web.Mvc.FilterAttribute. If you want to implement a filter, then you need to create a class that inherits from the FilterAttribute class and implements one or more of the IAuthenticationFilter, IAuthorizationFilter, IActionFilter, IResultFilter, or ExceptionFilter interfaces.
Now, we are going to create custom action filter, purpose is just passing a message to View. To do this, I have created a class and extended the AuthorizeAttribute class as:
In Controller code:
In the above discusion we try to understand what are action filters and how to create custom action filters. I hope it will help you.