C# 使用HttpClient PostAsJsonAsync调用我的API,如何正确地接受API中的复杂类型?
我正在使用C# 使用HttpClient PostAsJsonAsync调用我的API,如何正确地接受API中的复杂类型?,c#,api,asp.net-web-api,httpclient,C#,Api,Asp.net Web Api,Httpclient,我正在使用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",
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);
[Route("mytest")]
[HttpPost]
public HttpResponseMessage MyTest<T>(T foo)
{
//Do some stuff, and return the status code
return Request.CreateResponse(HttpStatusCode.OK);
}
然后在我的API中,我尝试获取foo
对象,并对其执行一些操作,然后返回HttpStatusCode
,如下所示:
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);
[Route("mytest")]
[HttpPost]
public HttpResponseMessage MyTest<T>(T foo)
{
//Do some stuff, and return the status code
return Request.CreateResponse(HttpStatusCode.OK);
}
[路线(“mytest”)]
[HttpPost]
公共HTTPResponseMessageMyTest(T-foo)
{
//做一些事情,然后返回状态码
返回Request.CreateResponse(HttpStatusCode.OK);
}
但这不起作用,当我使用
时,我得到一个500
错误
为了确保我能够获得api并在中传递一些内容,我将foo
更改为“someRandomString”
,然后在api中,我更改了MyTest
以如下方式接受字符串:公共HTTPResponseMessageMyTest(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和客户端应用程序之间共享。谢谢您的回复。就在您回复之前,我刚刚引用了相同的模型dll
,并打算尝试传递相同的模型。很高兴知道我走上了正确的道路。