我有以下API控制器:MVC Api Action&System.Web.Http.AuthorizeAttribute - 如何获取发布参数?
public class TestController : ApiController
{
[HttpPost]
[APIAuthorizeAttribute]
public IQueryable<Computers> ListOfComputersInFolder(Guid folderId)
{
return GetListOfComputersForFolder(folderId);
} // End of ListOfComputersInFolder
} // End of TestController
而下面是我的基本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);
}
}
说我有问题是,folderId
是走出空在onAuthorize方法。 (我基于this代码的获取者)。
在我看来,这应该是工作,但我似乎无法得到它。任何想法,我做错了什么,我应该如何去获得张贴的参数?
编辑:我试图直接与下面的读取后数据:
using (StreamReader inputStream = new StreamReader(request.InputStream))
{
output = inputStream.ReadToEnd();
}
request.InputStream.Position = 0;
这让我JSON格式的数据后,我可以再解析,但后来我的电话从来不使它虽然。我得到的响应以下异常:
<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)"}
编辑: 最后,好像这也可能会被使用的ApiController
,System.Web.Http.AuthorizeAttribute
和HttpPost
组合中的错误(它使用HttpGet
时不工作)。一个错误报告已经提交。
注意,因为这是一个[APIController] (http://msdn.microsoft.com/en-us/library/system.web.http.apicontroller(v=vs.108).aspx)而不是[Controller](http://msdn.microsoft.com /en-us/library/system.web.mvc.controller(v=vs.108 ).aspx),我使用'System.Web.Http.AuthorizeAttribute'而不是'System.Web.Mvc.AuthorizeAttribute'。我试着访问它的'ControllerContext.RouteData.Values [“folderId”],它仍然返回null。 – Kyle
@Zenox看到我更新的答案。 – James
谢谢我也看过这个,但仍然没有运气。 'actionContext.Request'类是[HttpRequestMessage](http://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessage_methods),不包含'GetRouteData'方法。另外,如果我看:actionContext.ControllerContext.RouteData.Values它只包含两个键:控制器和操作。我认为我最好的选择是从inputStream中读取发布数据。我试了一下,并确认我可以看到我的发布数据,但看起来有点冒失,所以我现在要继续寻找。 – Kyle