简体   繁体   English

如何在ASP.NET MVC2中向控制器添加自定义挂钩

[英]How to add custom hooks to controllers in ASP.NET MVC2

I've just started a new project in ASP.net 4.0 with MVC 2. 我刚刚在ASP.net 4.0中用MVC 2开始了一个新项目。

What I need to be able to do is have a custom hook at the start and end of each action of the controller. 我需要做的是在控制器的每个动作的开始和结束处都有一个自定义钩子。

eg 例如

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();
}

The View then see welcomeMessage as "Hi World" after being changed in the custom hook. 在自定义挂钩中更改后,View会将welcomeMessage视为“Hi World”。

The custom hook would need to be in an external file and not change the "core" compiled code. 自定义钩子需要在外部文件中,而不是更改“核心”编译代码。 This causes a problem as with my limited knowledge ASP.net MVC has to be compiled. 这导致了一个问题,因为我必须编译ASP.net MVC的有限知识。

Does anyone have any advice on how this can be achieved? 有没有人对如何实现这一点有任何建议?

Thanks 谢谢

You create your own class based on the ActionFilterAttribute . 您可以基于ActionFilterAttribute创建自己的类。 It has the following hooks. 它有以下钩子。

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

For example, 例如,

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);
    }
}

You can also check what type of [Action] the Action method is performing. 您还可以检查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
}

Oh I forgot to show how to use the attribute. 哦,我忘了展示如何使用该属性。
You just decorate on top of your Action Method. 你只需要在Action方法的基础上进行装饰。

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

An event based plugin system where you can dynamically call script code. 基于事件的插件系统,您可以在其中动态调用脚本代码。 So creating (for example) iron python scripts that get called when events are raised by the controller. 因此创建(例如)在控制器引发事件时调用的铁python脚本。

Doesn't have to be iron python, but that would make the most sense that I can see. 不一定是铁蟒,但这将是我能看到的最有意义的。

如何覆盖OnActionExecuting / OnActionExecuted并使用MEF(导入,导出其他汇编代码)?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM