问题描述
我创建一个自定义的 ActionFilterAttribute
,以便将的ViewResult
和重定向到 JsonResult
在Ajax请求秒。我有线大部分通过单元测试,我是出于某种原因,我的假设改造不得不发生在 OnResultExecuting
,我意识到这是没有的情况下,和正确的方法覆盖了 OnActionExecuted
,这是因为一旦操作方法返回的结果调用。
I'm creating a custom ActionFilterAttribute
in order to transform ViewResult
s and redirects into JsonResult
s during ajax requests. I've wired most of it through unit testing and I was for some reason assuming my transformation had to take place in OnResultExecuting
, I realized this was not the case, and the correct method to override was OnActionExecuted
, which is called as soon as the action method returns a result.
我的问题是什么时候到底是 OnResultExecuted
和 OnResultExecuting
被调用,因为我已经在所有四个覆盖断点和唯一的那些在 OnActionExecuting
和 OnActionExecuted
被解雇的。
My question is when exactly are OnResultExecuted
and OnResultExecuting
being called since I've breakpoints in all four overrides and only the ones in OnActionExecuting
and OnActionExecuted
are firing at all.
推荐答案
让我们来看看下面的例子它执行您所描述的转换:
Let's take the following example which performs the transformation you described:
public class MyActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
var result = filterContext.Result as ViewResultBase;
if (result != null && result.Model != null)
{
filterContext.Result = new JsonResult
{
Data = result.Model,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
}
}
的<$c$c>OnResultExecuting$c$c>方法将之前立即行动结果的<$c$c>ExecuteResult$c$c>法道和<$c$c>OnResultExecuted$c$c>法之后。
这篇关于当究竟OnResultExecuted和OnResultExecuting火?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!