【问题标题】:How to add custom hooks to controllers in ASP.NET MVC2如何在 ASP.NET MVC2 中向控制器添加自定义挂钩
【发布时间】:2013-04-07 06:06:28
【问题描述】:

我刚刚在 ASP.net 4.0 中使用 MVC 2 启动了一个新项目。

我需要做的是在控制器的每个动作的开始和结束处都有一个自定义钩子。

例如

public void Index() {  
    *** call to the start custom hook to externalfile.cs (is empty so does nothing)

    ViewData["welcomeMessage"] = "Hello World";

    *** call to the end custom hook to externalfile.cs (changes "Hello World!" to "Hi World")

    return View();
}

在自定义钩子中更改后,视图会将welcomeMessage 视为“Hi World”。

自定义挂钩需要位于外部文件中,并且不能更改“核心”编译代码。这会导致问题,因为我的知识有限,必须编译 ASP.net MVC。

有人对如何实现这一点有任何建议吗?

谢谢

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-2


    【解决方案1】:

    您根据ActionFilterAttribute 创建自己的类。它有以下钩子。

    1. OnActionExecuted
    2. OnActionExecuting
    3. OnResultExecuted
    4. OnResultExecuting

    例如,

    public class MyFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var controller = filterContext.Controller;
    
            controller.ViewData["welcomeMessage"] = "Hi World!";
            controller.TempData["Access_My_TempData"] = "Some Value";
    
            base.OnActionExecuted(filterContext);
        }
    }
    

    您还可以检查 Action 方法正在执行的 [Action] 类型。

    if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult))
    {
        // do something only if we are redirecting to a different action
    }
    else if (filterContext.Result is ViewResult)
    {
        // this is just a normal View action
    }
    

    哦,我忘了展示如何使用该属性。
    您只需在 Action Method 之上进行装饰。

    [MyFilterAttribute]
    public ActionResult MyActionMethod()
    {
        return View();
    }
    

    【讨论】:

    • 如果你不想手动把属性放到每个动作上,我相信你可以创建一个通用的基础控制器类型,然后把属性放到类型本身上。
    • 这看起来像是我希望做的事情。谢谢
    【解决方案2】:

    一个基于事件的插件系统,您可以在其中动态调用脚本代码。因此,创建(例如)当控制器引发事件时调用的 Iron python 脚本。

    不一定是铁蟒,但这是我能看到的最有意义的。

    【讨论】:

      【解决方案3】:

      如何覆盖 OnActionExecuting/OnActionExecuted 并使用 MEF(Import,Export other assembly code)?

      【讨论】:

      • 当这个概念已经在 MVC 框架中作为 ActionFilter 时,为什么还要使用 MEF?
      • 因为它认为动作过滤器中的动态注入代码被执行了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      • 2018-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-19
      相关资源
      最近更新 更多