Best way to abort/cancel action and response from ActionFilter

AgileMeansDoAsLittleAsPossible picture AgileMeansDoAsLittleAsPossible · Mar 3, 2011 · Viewed 27.6k times · Source

Best way to abort/cancel action from ActionFilter

I've got this ActionFilter, and it's suppose to end the connection immediately and return a 401 Unauthroized:

public class SignInRequired : ActionFilterAttribute 
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // User is verified, continue executing action

        if (Acme.Web.CurrentUser != null)
        {
            return;
        }

        // End response with 401 Unauthorized

        var response = HttpContext.Current.Response;
        response.StatusCode = (int)HttpStatusCode.Unauthorized;
        response.End();

        // Prevent the action from actually being executed

        filterContext.Result = new EmptyResult();
    }
}

I learned how you can cancel the action from executing by setting 'context.Result = new EmptyResult()` here, but I'm not sure if this is the best way to flush the response and close the connection.

Answer

Odeyinka Olubunmi picture Odeyinka Olubunmi · Aug 4, 2015

Setting the response will mean the action doesn't get called.

public override void OnActionExecuting(HttpActionContext actionContext)    
{ 
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
}

As other answers have said, though, authentication should be done with an AuthorizeAttribute (Docs for Web.API or for MVC).