[英]Using HttpClient PostAsJsonAsync to call my API, how do properly accept the complex type in the API?
我正在使用HttpClient
調用我的API。 我正在建立一個對象,並將其傳遞給PostAsJsonAsync
如下所示:
var foo = new Foo
{
//We will say these are the only two properties on the model:
Id = 1,
Name = "Test"
};
var response = await httpClient.PostAsJsonAsync("myApiPath/mytest", foo);
然后在我的API中,我試圖獲取foo
對象並對其進行處理,並返回如下HttpStatusCode
:
[Route("mytest")]
[HttpPost]
public HttpResponseMessage MyTest<T>(T foo)
{
//Do some stuff, and return the status code
return Request.CreateResponse(HttpStatusCode.OK);
}
但這不起作用,使用<T>
時出現500
錯誤。
只是為了確保能夠獲取api並傳遞一些信息,然后將foo
更改為"someRandomString"
,然后在API中將MyTest
更改為僅接受這樣的字符串: public HttpResponseMessage MyTest(string someRandomString) { }
,效果很好。
如何獲取復雜類型以正確地傳遞到API?
控制器動作不應是通用的:
[Route("mytest")]
[HttpPost]
public HttpResponseMessage MyTest(Foo foo)
{
//Do some stuff, and return the status code
return Request.CreateResponse(HttpStatusCode.OK);
}
當然, Foo
類與您在客戶端上具有的相同屬性相匹配。 為了避免代碼重復,您可以在一個單獨的項目中聲明合同,該合同將在Web和客戶端應用程序之間共享。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.