Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return status code Unauthorized for custom IActionFilter in WebAPI

I am working with asp.net WebAPI and I need to create a custom ActionFilter that does a quick check to see if the user requesting the URI should actually be able to get data back.

They have already been authorized to use the web service via basic auth and their role has been validated via a custom role provider.

The last thing I need to do is to check that they have permission to view the data they are requesting with a parameter in their URI.

Here is my code:

public class AccessActionFilter : FilterAttribute, IActionFilter     {          public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken, Func<System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>> continuation)         {              var result = //code to see if they have permission returns either 0 or 1              if (result==0) {                throw new ArgumentException("You do not have access to this resource");             }             return continuation();         }     }  

Currently I just throw an error which is not what I want, I'd rather return System.Net.HttpStatusCode.Unauthorized but I am a little miffed by the method I am overriding and I do not really understand it completely.

How would I go about returning that value?

like image 688
Slee Avatar asked Dec 14 '12 18:12

Slee


1 Answers

You are probably best sticking to an exception but using the HttpResponseException which will return an Http status code too.

throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized)); 

Good question here about this.

p.s.

It may be simpler/cleaner to implement ActionFilterAttribute

public class AccessActionFilter : ActionFilterAttribute {     public override void OnActionExecuting(HttpActionContext actionContext)     {         var result = //code to see if they have permission returns either 0 or 1          if (result==0)          {             throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));         }         base.OnActionExecuting(actionContext);     } 

}

like image 181
Mark Jones Avatar answered Sep 19 '22 15:09

Mark Jones