Objective
This article will give an introduction of Action Filter in ASP.Net MVC framework. This will also explain how to create a custom Action filter.
Action Filters in ASP.Net MVC framework
-
Action filters are attribute
-
This could be applied on a particular Action
-
This could be applied on a Controller.
-
This modifies the way Action executes.
-
Custom Action filter could also be created and applied.
ASP.Net MVC framework Action filters could be classified as,
How to use an Action filter?
-
Create a ASP.NET MVC application, by selection File->New->Project->Web
-
Right click on Controller folder and add one controller. Feel free to give any name. Here name is TestController.
-
Create an Action inside the controller. Feel free to give any name of the Action. Here name is TestingActionFilter()
-
TestingActionFilter() action is returning current time as string.
-
Apply Action filter OutputCache on the Action.
-
Give required parameter for OutputCache action filter.
7. Run the application.
8. Type http://localhost:1903/Test/TestingActionFilter to get the output. Port number may differ in your case.
Types of Action filter
Action filter class
-
The base class of all Action filter are ActionFilterAttribute class.
-
This is under namespace System.Web.Mvc
-
It extends FilterAttribute Class.
-
Class contains four methods , which is shown below
Creating a Custom Action Filter
-
Add a class in MVC project. Feel free to give any name.
-
Extend the class ActionFilterAttribute
-
Override the methods. Call method Message in all overridden function.
-
Custom Action filter class contains one method called Message. This method is simply writing name of the controller and action on Debug output.
-
On Action of TestController apply this custom Action filter.
-
See the output in Debug mode
Custom Action filter is writing name of the Controller and Action on Debug.
Conclusion
This article gave an introduction of Action Filter in ASP.Net MVC framework. This also explained how to create a custom Action filter.