我有以下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