[英]What part of the ASP.NET Web API framework translates a user-defined object to a HttpResponseMessage?
如果您在ApiController中有如下操作:
public Foo GetFoo(int id)
{
// ...
}
从另一个任何类型的.NET应用程序中,您可以像下面这样调用此API端点:
using (var client = new HttpClient())
{
var response = await client.PostAsJsonAsync("http://localhost/api/foo/1", value);
// ...
}
然后,即使API操作返回了用户定义的类Foo
对象, HttpClient.PostAsJsonAsync
方法也将返回Task<HttpResponseMessage>
。
此翻译在Web API的哪一部分进行? 客户端代码是否总是收到HttpResponseMessage
?
HttpClient不知道响应映射到foo类。 它只是返回封装为HttpResponseMessage的HTTP响应。
如果要将响应映射到Foo对象,则必须告诉它这样做。
例:
using (var client = new HttpClient())
{
var response = await client.PostAsJsonAsync("http://localhost/api/foo/1", value);
var stream = await response.Content.ReadAsStreamAsync(); // Read the request body into a stream.
// Map the body to a object of type Foo
var foo = new JsonMediaTypeFormatter().ReadFromStream(typeof(Foo), stream, Encoding.UTF8, null);
// Do whatever you want with foo...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.