如何以文本形式读取HttpResponseMessage内容 [英] How to read HttpResponseMessage content as text
问题描述
我将HttpResponseMessage类用作AJAX调用的响应,该调用从服务返回JSON数据.从服务返回AJAX调用后暂停执行时,我看到此类包含一个Content属性,该属性的类型为System.Net.Http.StreamContent.
I'm using HttpResponseMessage class as a response from an AJAX call which is returning JSON data from a service. When I pause execution after the AJAX call comes back from the service, I see this class contains a Content property which is of type System.Net.Http.StreamContent.
如果在浏览器中进行检查,我会看到成功进行了网络调用,并以JSON数据作为响应.我只是想知道为什么我无法在Visual Studio中看到返回的JSON文本?我在整个System.Net.Http.StreamContent对象中进行了搜索,没有看到任何数据.
If I inspect in the browser I see the network call being made successfully and the JSON data as the response. I'm just wondering why I cannot see the returned JSON text from within Visual Studio? I searched throughout this System.Net.Http.StreamContent object and see no data.
public async Task<HttpResponseMessage> Send(HttpRequestMessage request) {
var response = await this.HttpClient.SendAsync(request);
return response;
}
推荐答案
The textual representation of the response is hidden in the Content
property of the HttpResponseMessage
class. Specifically, you get the response like this:
response.Content.ReadAsStringAsync();
类似于所有现代的 Async 方法,ReadAsStringAsync
返回Task
.要直接获得结果,请使用任务的Result
属性:
Like all modern Async methods, ReadAsStringAsync
returns a Task
. To get the result directly, use the Result
property of the task:
response.Content.ReadAsStringAsync().Result;
请注意,Result
正在阻止.您也可以await
ReadAsStringAsync()
.
Note that Result
is blocking. You can also await
ReadAsStringAsync()
.
这篇关于如何以文本形式读取HttpResponseMessage内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!