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?
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); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With