ASP.NET MVC 生命周期 - 每个页面请求做一些工作

ASP.NET MVC Lifecycle - Do Some Work Once Per Page Request

我想根据对 .NET MVC Web 应用程序的 Web 请求执行一些工作。具体来说,我想为每个页面加载在数据库中创建一个日志条目。

在覆盖的 Controller class Controller.Initialize() 方法中执行此工作不起作用,因为 new controller is created with every call to @Html.Action()。因此,如果从视图调用子操作,那么我最终会进行双重记录——这不是我想要的。

如何将一些工作插入 MVC 生命周期,以便它在每个页面请求中执行一次?

如果该操作是子操作,您可以签入 Initialize

ControllerContext.IsChildAction

您可以使用 OnActionExecutingOnActionExecuted

例如,

public class HomeController : Controller
{
    [LogActionFilter]
    public ActionResult Index()
    {
        return View();
    }
}

public class LogActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // If you register globally, you need this check.
        if (!filterContext.IsChildAction)
        {
           Log("OnActionExecuting", filterContext.RouteData);
        }
        base.OnActionExecuting(filterContext);
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // If you register globally, you need this check.
        if (!filterContext.IsChildAction)
        {
           Log("OnActionExecuted", filterContext.RouteData);
        }
        base.OnActionExecuted(filterContext);
    }

    private void Log(string methodName, RouteData routeData)
    {
        var controllerName = routeData.Values["controller"];
        var actionName = routeData.Values["action"];
        var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
        Debug.WriteLine(message, "Action Filter Log");
    }
}