Can you apply ActionFilter in ASP.NET-MVC for EVERY action

I want to apply an ActionFilter in ASP.NET MVC for EVERY action that I have in my application - on every controller.

Is there a way to do this without applying it to every ActionResult method?

+6
asp.net-mvc actionresult
source share
3 answers

Yes, you can do it, but that’s not how it works out of the box. I have done the following:

  • Create a base controller class and inherit all your controllers.
  • Create an action filter attribute and inherit it from FilterAttribute and IActionFilter
  • Decorate the base controller class with a new action filter attribute

Here is an example of an action filter attribute:

public class SetCultureAttribute : FilterAttribute, IActionFilter { #region IActionFilter implementation public void OnActionExecuted(ActionExecutedContext filterContext) { //logic goes here } public void OnActionExecuting(ActionExecutingContext filterContext) { //or logic goes here } #endregion IActionFilter implementation } 

Here is an example of a controller base class with this attribute:

 [SetCulture] public class ControllerBase : Controller { ... } 

Using this method, if controller classes are inherited from ControllerBase, then the SetCulture action filter will always be executed. I have a complete sample and a post on this on my blog if you want a little more detail.

Hope this helps!

+9
source share

How things get better ... 2 years later we

 public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorElmahAttribute()); } 
+4
source share

You do not need to apply it to each action, you can simply apply it to each controller (i.e. put the attribute in a class, not in a method).

Or, as Yang noted, you can put it in the base class of the controller, and then move from that controller.

0
source share

All Articles