[英]What part of the ASP.NET Web API framework translates a user-defined object to a HttpResponseMessage?
If you have a action in an ApiController like so: 如果您在ApiController中有如下操作:
public Foo GetFoo(int id)
{
// ...
}
And from another .NET application of any type, you call this API end-point like so: 从另一个任何类型的.NET应用程序中,您可以像下面这样调用此API端点:
using (var client = new HttpClient())
{
var response = await client.PostAsJsonAsync("http://localhost/api/foo/1", value);
// ...
}
Then, the HttpClient.PostAsJsonAsync
method returns a Task<HttpResponseMessage>
even when the API action returned a user-defined object of class Foo
. 然后,即使API操作返回了用户定义的类Foo
对象, HttpClient.PostAsJsonAsync
方法也将返回Task<HttpResponseMessage>
。
What part of the Web API does this translation? 此翻译在Web API的哪一部分进行? Does the client code always receive a HttpResponseMessage
? 客户端代码是否总是收到HttpResponseMessage
?
HttpClient doesn't know that the response maps to the foo class. HttpClient不知道响应映射到foo类。 It simply returns the HTTP response encapsulated as a HttpResponseMessage. 它只是返回封装为HttpResponseMessage的HTTP响应。
If you want to map the response to a Foo object you must tell it to do so. 如果要将响应映射到Foo对象,则必须告诉它这样做。
Example: 例:
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.