Question

I am a bit confused as to when ActionResult actually gets evaluated.

When using the Authorize attribute, I can see that if the user is not authorized, the result context gets set to an unauthorized result:

filterContext.Result = new HttpUnauthorizedResult();

However, the AuthorizeAttribute does not do the redirect, instead, it simply sets the context which just "flows" through the .NET pipeline until something converts that into a 401 header.

My question is what in .Net actually does the convertion?

Was it helpful?

Solution

I am a bit confused as to when ActionResult actually gets evaluated.

ActionResult get evaluated (not flushed to HTTP response or client) after IResultFilter.OnResultExecuting and before IResultFilter.OnResultExecuted

Now what you are demonstrating with Authorize attribute is Action filter and it enable developer to alter/change action result within Action Filter life cycle. Here in Authorize attribute if user is not authenticated then it is changing action result to HttpUnauthorizedResult. Now what you are saying that

something converts that into a 401 header

but actually it is HttpUnauthorizedResult which set response header 401 while instantiating ActionResult object. Once ActionResult is instantiated it will be flushed to HTTP response pipeline.

OTHER TIPS

After a little bit of digging around, I see that all ActionResults inherit from the abstract class ActionResult, which has one abstract method: ExecuteResult

public abstract class ActionResult
{
    public abstract void ExecuteResult(ControllerContext context);
}

It is this method that each action result implements with their own logic.

So for instance, JsonResult needs to specify the ContentType:

response.ContentType = "application/json";

While FileResult sets the "Content-Disposition" header:

context.HttpContext.Response.AddHeader("Content-Disposition", headerValue);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top