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

后端 未结 3 1637
渐次进展
渐次进展 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 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());
        }
    

提交回复
热议问题