Is it possible to create a global action filter that will automatically apply to all actions in all controllers in ASP.NET MVC application? I want something like "before_filter" defined in ApplicationController in Ruby on Rails.
Thank you for your help.
The global filters will be applied to all the controller and action methods of an application. The [HandleError] filter is applied globally in the MVC application by default in every MVC application created using Visual Studio, as shown below. Example: Register Global Filters.
ASP.NET MVC 3.0 introduces global action filters - an easy way to apply an action filter to every action in an MVC application. All you need to do is register the filters during application startup: protected void Application_Start() { ... GlobalFilters.
The ASP.NET MVC Framework supports four different types of filters.
This really depends what you want to do with it. In many scenarios, the previous answers by vucetica and Adeel will be what you actually want to do. However, neither of them meet the criteria you listed: automatically apply to all actions/controllers.
To do something like that, you would need to implement a handler for the Application BeginRequest event in Global.asax. See the MSDN documentation for more information.
Update - July 27, 2010: ScottGu blogged about MVC 3 Preview 1, which includes a framework for global filters like you're talking about. They're registered via Global.asax, and can apply to all controllers or based on specific criteria.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With