views:

180

answers:

3

Is there a way to have an action filter, like

public class MyActionFilterAttribute : ActionFilterAttribute {
    public override void OnActionExecuting(ActionExecutingContext context) {
    ...

be automatically applied to all actions in a web site?

+5  A: 

I don't believe there is an out-of-the-box way to do this. The easiest thing to do for simple sites is just apply the filter at the Controller level. This is pretty common, and generally it's a good idea to have your own base controller class in case things like this crop up where you want to propagate it to all your controllers. E.g.:

[MyActionFilter]
public class MyBaseController : Controller
{
  ...
}

public class HomeController : MyBaseController
{
  ...
}

That being said, here is a blog post showing how you can achieve application wide action filters. Looks like a small amount of work, but perhaps you can use this technique.

womp
+2  A: 
  1. You can apply it to an entire controller class to have it affect all actions on a controller.
  2. You can apply it to a base controller class and have all your controllers inherit from that controller, thus getting the effect of applying the filter to all controllers.
  3. You can use a base controller class and override the OnActionExecuting method directly on the controller which is probably more appropriate than using a filter if your intent is to apply your filter code on all actions across the board.
Nathan Ridley
By two, you mean applying it to the Controller class provided by ASP.NET MVC? Is that possible? How?
J. Pablo Fernández
No, he means that all of your controllers should inherit from a base controller class that you would write, which extended the asp.net mvc controller. On your base controller class, you would tag it with the filter.
womp
What womp said.
Nathan Ridley
A: 

Where NewlyCreatedActionFilter is the ActionFilter you're creating, obviously. :)

[NewlyCreatedActionFilter]
public class Basecontroller : Controller
{
  ...
}

public class HomeController : BaseController
{
  ...
}

public class AccountController : BaseController
{
  ...
}

Both of these controller classes would inherit from BaseController, so the NewlyCreatedActionFilter filter is applied to all.

Dan Atkinson