ASP.NET MVC: Execute code on all Actions (global OnActionExecuting?)

后端 未结 3 1625
渐次进展
渐次进展 2021-02-06 11:07

Is there a \"global\" OnActionExecuting that I can override to have all my MVC actions (regardless of controller) do something when they get called? If so, how?

相关标签:
3条回答
  • 2021-02-06 11:51

    Nope. The easiest way to do this is to write a common base class that all of your controller types subclass, then stick an action filter on that base class or override its OnActionExecuting() method.

    0 讨论(0)
  • 2021-02-06 11:57

    Asp.net MVC3 added support for Global Filters

    From the ScottGu blog:

    ASP.NET MVC supports the ability to declaratively apply “cross-cutting” logic using a mechanism called “filters”. You can specify filters on Controllers and Action Methods today using an attribute syntax like so:

    image

    Developers often want to apply some filter logic across all controllers within an application. ASP.NET MVC 3 now enables you to specify that a filter should apply globally to all Controllers within an application. You can now do this by adding it to the GlobalFilters collection. A RegisterGlobalFilters() method is now included in the default Global.asax class template to provide a convenient place to do this (it is then called by the Application_Start() method):

    image

    The filter resolution logic in MVC 3 is flexible so that you can configure a global filter that only applies conditionally if certain conditions are met (for example: debugging is enabled, or if a request uses a particular http verb, etc). Filters can also now be resolved from a Dependency Injection (DI) container.

    0 讨论(0)
  • 2021-02-06 12:01

    Create one class that Implements IActionFilter and/or IResultFilter:

    public class FilterAllActions : IActionFilter, IResultFilter
    {      
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            throw new System.NotImplementedException();
        }
    
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            throw new System.NotImplementedException();
        }
    
        public void OnResultExecuting(ResultExecutingContext filterContext)
        {
            throw new System.NotImplementedException();
        }
    
        public void OnResultExecuted(ResultExecutedContext filterContext)
        {
            throw new System.NotImplementedException();
        }
    }
    

    And register it on Global.asax

        protected void Application_Start()
        {
            //...
            RegisterGlobalFilters(GlobalFilters.Filters);
            //...
        }
    
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new FilterAllActions());
        }
    
    0 讨论(0)
提交回复
热议问题