views:

133

answers:

4

Dear Experts,

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.

+1  A: 

Create your own base controller and inherit from it.

vucetica
Thank you, it should work, but I'm looking for a really simple approach that will not require much coding.
Evgeny
@vucetice You should favor composition over inheritance
Arnis L.
+3  A: 

yes it is possible. Check Action Filters

Adeel
Thank you. Yes, that's what I'm using currently. I just wanted to know if there is a simple way to create a global filter that will work automatically for everything without assigning attributes to controllers and actions. That's what GalacticCowboy underlined in his reply.
Evgeny
@Evgeny if you place action filter attribute on Controller, it will be applied on all actions. you don't need to place for each action.
Adeel
Apparently he doesn't even want to do that... Though you're right, this is the best way to do it.
GalacticCowboy
Evgeny
+1  A: 

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.

GalacticCowboy
Thank you for your answer. First I thought it would work but after trying this approach I noticed that Application_BeginRequest gets ALL the requests, including requests for .js, .css, .jpg and other resources for the page. So it would be run many times for one page and may be a serious overload. Is there an easy way to filter only the request for the page content and skip all the .js, .css, .jpg requests without parsing the requested URL?
Evgeny
You might be able to look at the information coming out of the routing engine to determine if you're dealing with a controller/action. Honestly, Adeel's answer is the *right* way to do something like this, I was just pointing out that this is the alternative if you wanted an automatic, global handler.
GalacticCowboy
If you don't want to wait for MVC3, my coworker wrote something that we use to automatically match filters with actions (either always, or based on a condition). This is dependent on Windsor for IOC but you can always modify that part. http://geekswithblogs.net/wesm/archive/2009/12/11/ijoined-filter.aspx
Ryan
A: 

You can try to use FluentFilter library.

baNguit