bevacqua bevacqua - 2 months ago 7
ASP.NET (C#) Question

When exactly do OnResultExecuted and OnResultExecuting fire?

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.

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.

Answer

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.