devlife
devlife

Reputation: 16155

How to get Result type from ControllerContext

Is it possible to get the Action result type (ViewResult, JsonResult, etc) from an instance of ControllerContext?

Upvotes: 3

Views: 1715

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039278

No, that's not possible. The controller runs much earlier than any ActionResults. But if you are writing an ActionFilter you could get that information from the filterContext using its Result property.

For example:

public class MyGlobalActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var result = filterContext.Result;
        if (result is ViewResultBase)
        {
            // the controller action returned a view result 
            // (either a ViewResult or PartialViewResult)
        }
        else if (result is JsonResult)
        {
            // the controller action returned a JSON result
        }
        else if (result is RedirectToRouteResult)
        {
            // the controller action redirected
        }
        .... and so on
    }
}

Bear in mind that this makes sense only once the controller action has finished executing, a.k.a only inside OnActionExecuted, OnResultExecuting and OnResultExecuted. It makes no sense to be attempting to verify what result did the controller action returned before this action has finished executing.

Upvotes: 7

Related Questions