How to: Create a Custom Action Filter
An action filter consists of logic that runs directly before or directly after an action method runs. You can use action filters for logging, authentication, output caching, or other tasks.
You implement an action filter as an attribute that inherits from the ActionFilterAttribute class. You override the OnActionExecuting method if you want your logic to run before the action method. You override the OnActionExecuted method if you want your logic to run after the action method. After you define an action filter, you can use the attribute to mark any action methods that you want the filter to apply to.
This topic describes how to create an action filter and use the attribute to mark one or more action methods.
To create an action filter
In Visual Studio, open the MVC application project that you want to add the action filter to.
In Solution Explorer, right-click the Controllers folder, click Add, and then click New Item.
The Add New Item dialog box is displayed.
Under Templates, select the Class template.
In the Name box, enter the name of the action filter attribute class that you are creating.
By convention, the name of your action filter attribute should end with "Attribute", such as LogFilterAttribute or OutputFilterAttribute.
The class is added to your project.
In the new class, add code so that it inherits from the ActionFilterAttribute class, as shown in the following example:
If you want the filter to run directly before an action method, override the OnActionExecuting method and add your logic.
The following example shows a skeleton OnActionExecuting method.
Public Overrides Sub OnActionExecuting(ByVal filterContext As _ ActionExecutingContext) ' The action filter logic. End Sub
If you want the filter to run directly after an action method, override the OnActionExecuted method and add your logic.
The following example shows a skeleton OnActionExecuted method.
Public Overrides Sub OnActionExecuted(ByVal filterContext As _ ActionExecutedContext) ' The action filter logic. End Sub
In controller classes, add the filter attribute to any action method that you want the filter to apply to.
The following example shows an Index action method that has been marked with the CachingFilter action filter.