Global Action Filters in ASP.NET MVC 3
Action Filters are a great way to handle cross-cutting concerns in ASP.NET MVC such as Logging, ExceptionHandling, etc. In previous versions of MVC3, action filters have to be explicitly added to each controller.
MVC3 adds the concept of Global Action Filters which allow you to apply action filters globally without the need for explicit declaration. In this example, we’ll demonstrate how to add a debug action filter attribute that shows debug information for each view using Global Action Filters.
This action filter uses the StopWatch object to clock how long the action took to execute, and displays that information in a view.
It’s applied normally by adding the “DebugInfo” attribute to the top of a controller class, as below.
This results in the output seen below on our views:
If we click the “LogOn” link on our default application, we won’t see this information as we haven’t applied this filter to the “Account” controller. Lets see how we can set an action filter to display gloablly.
Registering Global Action Filters
MVC3 adds a new function into our Global.asax called Register Global Filters. To apply a filter globally, simply add a new line specifying your action filter as below.
Now, when we click on the “Log On” link, we can see the DebugInfo filter has been automatically applied to the Account controller.