Kyle Kyle - 1 month ago 9
C# Question

MVC Api Action & System.Web.Http.AuthorizeAttribute - How to get post parameters?

I have the following API Controller:

public class TestController : ApiController
{
[HttpPost]
[APIAuthorizeAttribute]
public IQueryable<Computers> ListOfComputersInFolder(Guid folderId)
{
return GetListOfComputersForFolder(folderId);
} // End of ListOfComputersInFolder
} // End of TestController


And the following is my basic
APIAuthorizeAttribute
.

public class APIAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
var Request = System.Web.HttpContext.Current.Request;
var folderId = Request.RequestContext.RouteData.Values["folderId"] ?? Request.Params["folderId] as string;
if(null == folderId)
{
folderId = actionContext.ControllerContext.RouteData.Values["folderId"];
}

base.OnAuthorization(actionContext);
}
}


The problem that I'm having is that
folderId
is coming out null in the onAuthorize method. (I based the fetcher on this code).

It seems to me that this should be working, but I cannot seem to get it to. Any ideas on what I am doing wrong and how I should go about getting the posted parameter?

Edit: I tried reading the post data directly with the following:

using (StreamReader inputStream = new StreamReader(request.InputStream))
{
output = inputStream.ReadToEnd();
}
request.InputStream.Position = 0;


Which gets me the post data in JSON format which I could then parse, but then my call never makes it though. I get the following exception in the Response:

<h2>500 - Internal server error.</h2>
<h3>There is a problem with the resource you are looking for, and it cannot be displayed.

at System.Json.JXmlToJsonValueConverter.JXMLToJsonValue(Stream jsonStream, Byte[] jsonBytes)\u000d\u000a at System.Net.Http.Formatting.JsonMediaTypeFormatter.<>c__DisplayClass7.<OnReadFromStreamAsync>b__6()\u000d\u000a at System.Net.Http.Internal.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"}


EDIT:
In the end, it seems like this could possibly be a bug with the combination of
ApiController
,
System.Web.Http.AuthorizeAttribute
and
HttpPost
(it does work when using
HttpGet
). A bug report has been submitted.

Answer

The AuthorizeAttribute should have an AuthorizationContext parameter rather than a HttpActionContext one, from that you should be able to access the RouteData e.g.

public override void OnAuthorization(AuthorizationContext filterContext)
{
    var folderId = filterContext.RouteData.Values["folderId"];
    ...
}

Update

Noticed you are using ApiController and as such using Http.AuthorizeAttribute (explains why you don't have an AuthorizationContext). In that case, you can get the RouteData via the action context e.g.

var folderId = actionContext.Request.GetRouteData().Values["folderId"];
Comments