By its very nature, an AuthoriseAttribute looks like it is called in the pipeline before the model bindings and parameter bindings are started. You also encounter problems accessing and reading Request.Content ... it can only be done once , and if you are going to try it in your auth attribute, you can break mediaTypeFormater ...
in WebAPI, the request body (HttpContent) can be a stream without restrictions, read-only, without buffering.
Update There are different ways to specify the execution context ... http://msdn.microsoft.com/en-us/library/system.web.http.filters.filterscope(v=vs.108).aspx . The authorized attribute is Global, so itโs too early for it to access action information.
Given that you want to access the model and parameters, you can slightly change your approach and use the OnActionExecuting filter (โActionโ scope) and throw 401 or 403 based on your check.
This filter is called later at runtime, and therefore you have full access to the associated data.
A very simple example below:
public class ApiAuthorizationFilter : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { Foo model = (Foo)actionContext.ActionArguments["model"]; string param1 = (string)actionContext.ActionArguments["param1"]; int param2 = (int)actionContext.ActionArguments["param2"]; if (model.Id != "1") throw new HttpResponseException(System.Net.HttpStatusCode.Forbidden); base.OnActionExecuting(actionContext); } }
Controller example:
public class Foo { public string Id { get; set; } public DateTime Time { get; set; } } public class FoosController : ApiController {
What the other answers said ... they are right if you can access everything you need at the URL, get information through a request; however, I think the model and content of the request should be left alone:
var queryStringCollection = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query); //example for param1 string param1 = queryStringCollection["param1"]; //example for param2 int param2 = int.Parse(queryStringCollection["param2"]); //Example of getting the ID from the URL var id = actionContext.Request.RequestUri.Segments.LastOrDefault();
Mark Jones Oct 10 '12 at 21:10 2012-10-10 21:10
source share