我想对.NET MVC Web应用程序的每个Web请求执行一些工作。具体来说,我想为每个页面加载在数据库中创建一个日志条目。
在覆盖的Controller类Controller.Initialize()
方法中执行此工作不起作用,因为new controller is created with every call to @Html.Action()。因此,如果从视图中调用子操作,那么我最终会进行双重日志记录 - 这不是我想要的。
如何在MVC生命周期中插入一些工作,以便每页请求执行一次?
答案 0 :(得分:3)
您可以使用 OnActionExecuting 或 OnActionExecuted 。
例如,
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");
}
}
答案 1 :(得分:1)
如果操作是儿童行动,您可以查看Initialize
。
ControllerContext.IsChildAction