我正在使用
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 中?
控制器操作不应该是通用的:
[Route("mytest")]
[HttpPost]
public HttpResponseMessage MyTest(Foo foo)
{
//Do some stuff, and return the status code
return Request.CreateResponse(HttpStatusCode.OK);
}
当然,
Foo
类与您在客户端上拥有的相同属性相匹配。为了避免代码重复,您可以在一个单独的项目中声明您的合约,该项目将在您的 Web 和客户端应用程序之间共享。