What are the types of action filters available in ASP.NET MVC framework?
In this post I’ll list and explain you what are the types of action filters available in ASP.NET MVC framework and how you can use them.
If you would like to apply any pre or post processing logic to a controller action and it’s result, ASP.NET MVC framework provides what is called as action filters that can be used in your application. An action filter can be consumed at different levels like at controller or action or global level. If a filter is applied to just an action, it’s only available to that action. If it is applied at controller level, it works for all the actions inside that controller. And self explanatory, if it is defined at the global level, i.e. using FilterConfig in Global.asax.cs file, then it applies to all of the controllers and thus, actions.
Action filters are very powerful as it allows you to intercept the action’s requesting, requested and result’s executing, executed methods to perform some custom processing that your application needs. This can be very useful if you don’t want to rewrite some piece of code for every action or controller and that’s a good way to roll your own action filter.
Let us look at the table below that lists all the out of the box action filters available to us in ASP.NET MVC framework. Use the referenced links in the table to learn more about that attribute with practical examples.
Types of Action Filters available in ASP.NET MVC
|OutputCache||OutputCacheAttribute class is used to mark an action method or controller whose output will be cached.|
|ValidateInput||ValidateInputAttribute class is used to mark action methods whose input must be validated.|
|Authorize||AuthorizeAttribute class is used to specify that access to a controller or action method is
restricted to users who meet the authorization requirement. Example, on the basis of roles, user-names, etc.
|ValidateAntiFrogeryToken||ValidateAntiForgeryTokenAttribute class is used to prevent cross site request forgeries.|
|HandleError||HandleErrorAttribute class is used to handle an exception that is thrown by an action
method. Example, specify a view to render in the event of an unhandled exception.
It is quite likely that you will need to extend the existing filters available in the framework or write from scratch. Learn how to write a custom action filter so as to not repeat the same logic of code for every controller or action. I’ll be adding some examples to how to use the filters mentioned in the table above. So, keep an eye on my blog to learn about it.