【问题标题】:ASP.NET MVC: Execute code on all Actions (global OnActionExecuting?)ASP.NET MVC:在所有操作上执行代码(全局 OnActionExecuting?)
【发布时间】:2009-09-16 04:29:46
【问题描述】:

是否有一个“全局”的 OnActionExecuting 我可以覆盖它以让我的所有 MVC 操作(无论控制器如何)在被调用时执行某些操作?如果有,怎么做?

【问题讨论】:

  • 你想在什么环境下做这个?

标签: c# asp.net-mvc


【解决方案1】:

Asp.net MVC3 添加了对Global Filters的支持

来自 ScottGu 博客:

ASP.NET MVC 支持使用称为“过滤器”的机制以声明方式应用“横切”逻辑的能力。您现在可以使用如下属性语法在控制器和操作方法上指定过滤器:

开发人员通常希望在应用程序中的所有控制器上应用一些过滤器逻辑。 ASP.NET MVC 3 现在允许您指定过滤器应全局应用于应用程序中的所有控制器。您现在可以通过将其添加到 GlobalFilters 集合来执行此操作。 RegisterGlobalFilters() 方法现在包含在默认 Global.asax 类模板中,以提供一个方便的地方来执行此操作(然后由 Application_Start() 方法调用):

MVC 3 中的过滤器解析逻辑很灵活,因此您可以配置一个全局过滤器,该过滤器仅在满足某些条件时有条件地应用(例如:启用调试,或者如果请求使用特定的 http 动词等)。过滤器现在也可以从依赖注入 (DI) 容器中解析。

【讨论】:

    【解决方案2】:

    不。最简单的方法是编写一个公共基类,将所有控制器类型作为子类,然后在该基类上粘贴一个操作过滤器或覆盖其 OnActionExecuting() 方法。

    【讨论】:

    • 请注意 MVC 3 添加了对全局过滤器的支持
    【解决方案3】:

    创建一个实现 IActionFilter 和/或 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();
        }
    }
    

    并在 Global.asax 上注册

        protected void Application_Start()
        {
            //...
            RegisterGlobalFilters(GlobalFilters.Filters);
            //...
        }
    
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new FilterAllActions());
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-18
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      • 2019-10-03
      • 1970-01-01
      相关资源
      最近更新 更多