When exactly do OnResultExecuted and OnResultExecuting fire?

后端 未结 2 2141
执念已碎
执念已碎 2021-02-18 13:21

I\'m creating a custom ActionFilterAttribute in order to transform ViewResults and redirects into JsonResults during ajax requests. I\'ve

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-18 13:54

    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)
        {
        }
    }
    

    The OnResultExecuting method will be invoked immediately before the action result's ExecuteResult method runs and the OnResultExecuted method immediately after.

提交回复
热议问题