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

六眼飞鱼酱① 提交于 2019-12-04 22:08:16

问题


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

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


回答1:


Yes, you can do this but it's not the way it works out of the box. I did the following:

  1. Create a base controller class and have all of your controllers inherit from it
  2. Create an action filter attribute and have it inherit from FilterAttribute and IActionFilter
  3. Decorate your base controller class with your new action filter attribute

Here's a sample of the 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's a sample of the base controller class with this attribute:

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

Using this method as long as your controller classes inherits from ControllerBase then the SetCulture action filter would always be executed. I have a full sample and post on this on my blog if you'd like a bit more detail.

Hope that helps!




回答2:


How things get better...2 years later we have

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorElmahAttribute());
    }



回答3:


You don't have to apply it to every action, you can just apply it to every controller (ie. put the attribute on the class, not the method).

Or, as Ian mentioned, you can put it on a base controller class and then extend from that controller.



来源:https://stackoverflow.com/questions/649409/can-you-apply-an-actionfilter-in-asp-net-mvc-on-every-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!