ASP.NET MVC里面我们要自定义ActionFilter的时候会发现有4个方法可以override:OnActionExecuting,OnActionExecuted,OnResultExecuting,OnResultExecuted。他们分别在什么时候执行一直是困扰人类的一个问题。我代表人类做了一个简单的实验:
首先自定义一个ActionFilter,每个方法执行的时候都在VS的OUTPUT窗口输出信息:
public class TestActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Debug.WriteLine("OnActionExecuting");
base.OnActionExecuting(filterContext);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
Debug.WriteLine("OnActionExecuted");
base.OnActionExecuted(filterContext);
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
Debug.WriteLine("OnResultExecuting");
base.OnResultExecuting(filterContext);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
Debug.WriteLine("OnResultExecuted");
base.OnResultExecuted(filterContext);
}
}
Controller里为了搞清执行顺序,也需要输出:
[TestActionFilter]
public ActionResult Index()
{
Debug.WriteLine("Before return View()");
return View();
}
最后是View:
@{
Debug.WriteLine("Hello from Index.cshtml");
}
执行结果是这样的,有图有JJ:
1. OnActionExecuting
2. Before return View()
3. OnActionExecuted
4. OnResultExecuting
5. Hello from Index.cshtml
6. OnResultExecuted