Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to abort/cancel action and response from ActionFilter

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.

like image 907
AgileMeansDoAsLittleAsPossible Avatar asked Mar 03 '11 20:03

AgileMeansDoAsLittleAsPossible


1 Answers

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).

like image 192
Odeyinka Olubunmi Avatar answered Sep 30 '22 02:09

Odeyinka Olubunmi