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

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

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

关于c# - 如何在 ASP.NET MVC2 中向 Controller 添加自定义 Hook ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2928122/

相关文章:

asp.net-mvc - 枚举的 IRouteConstraint

c# - 十进制舍入扩展错误 - 无法使用实例引用访问;用类型名称限定它

c# - SafeWaitHandle 与 SafeFileHandle c#

c# - 在asp.net mvc中仅刷新页面导航中母版页中的内容面板

c# - 如何在 MVC 中定义 @Html.DisplayFor 的最大长度?

c# - 对依赖于请求的 URL 参数的 Controller 属性进行单元测试 (ASP.NET MVC)

c# - linq中的多个交叉引用表连接

c# - SignalR 意外响应代码 : 500

ASP.NET MVC与Webforms : Replacing WebForms Controls

c# - MVC2 DropDownListFor 问题,仅显示类名