Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global action filter in ASP.NET MVC

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.

like image 778
Evgenii Avatar asked Jul 26 '10 11:07

Evgenii


People also ask

What is global filter in MVC?

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.

How do I apply an action filter globally?

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.

How many types of action filters are there in MVC?

The ASP.NET MVC Framework supports four different types of filters.


1 Answers

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.

like image 98
GalacticCowboy Avatar answered Jan 03 '23 17:01

GalacticCowboy