Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Result type from ControllerContext

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

like image 548
devlife Avatar asked Aug 19 '26 15:08

devlife


1 Answers

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.

like image 56
Darin Dimitrov Avatar answered Aug 23 '26 03:08

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!