我正在使用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);
}
但是这不起作用,当我使用500
时出现<T>
错误。
为了确保我能够获得api并传递内容,我将foo
更改为"someRandomString"
,然后在API中我将MyTest
更改为仅接受像这样的字符串:public HttpResponseMessage MyTest(string someRandomString) { }
,并且工作正常。
如何让复杂类型正确传递到API?
答案 0 :(得分:2)
控制器操作不应该是通用的:
[Route("mytest")]
[HttpPost]
public HttpResponseMessage MyTest(Foo foo)
{
//Do some stuff, and return the status code
return Request.CreateResponse(HttpStatusCode.OK);
}
当然Foo
类与客户端上的相同属性匹配。为了避免代码重复,您可以在一个单独的项目中声明您的合同,该项目将在您的Web和客户端应用程序之间共享。