Skip to main content
 首页 » 编程设计

c#之如何在 ASP.NET MVC2 中向 Controller 添加自定义 Hook

2024年02月24日27sharpest

我刚刚在 ASP.net 4.0 和 MVC 2 中开始了一个新项目。

我需要做的是在 Controller 的每个 Action 开始和结束时有一个自定义 Hook 。

例如

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

在自定义 Hook 中更改后,View 会将 welcomeMessage 视为“Hi World”。

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

有没有人对如何实现这一目标有任何建议?

谢谢

请您参考如下方法:

您根据 ActionFilterAttribute 创建自己的类.它具有以下钩子(Hook)。

  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 
} 

哦,我忘了展示如何使用该属性。
您只需在操作方法之上进行装饰即可。

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