C# 如何将 HttpResponseMessage 内容读取为文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29975001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read HttpResponseMessage content as text
提问by PythonIsGreat
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.
我使用 HttpResponseMessage 类作为 AJAX 调用的响应,该调用从服务返回 JSON 数据。当我在 AJAX 调用从服务返回后暂停执行时,我看到这个类包含一个 System.Net.Http.StreamContent 类型的 Content 属性。
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.
如果我在浏览器中检查,我会看到网络调用成功进行,并且 JSON 数据作为响应。我只是想知道为什么我在 Visual Studio 中看不到返回的 JSON 文本?我搜索了整个 System.Net.Http.StreamContent 对象,但没有看到任何数据。
public async Task<HttpResponseMessage> Send(HttpRequestMessage request) {
var response = await this.HttpClient.SendAsync(request);
return response;
}
采纳答案by Bart van Nierop
The textual representation of the response is hidden in the Contentproperty of the HttpResponseMessageclass. Specifically, you get the response like this:
响应的文本表示隐藏在类的Content属性中HttpResponseMessage。具体来说,您会得到如下响应:
response.Content.ReadAsStringAsync();
response.Content.ReadAsStringAsync();
Like all modern Asyncmethods, ReadAsStringAsyncreturns a Task. To get the result directly, use the Resultproperty of the task:
像所有现代异步方法一样,ReadAsStringAsync返回一个Task. 要直接获取结果,请使用Result任务的属性:
response.Content.ReadAsStringAsync().Result;
response.Content.ReadAsStringAsync().Result;
Note that Resultis blocking. You can also awaitReadAsStringAsync().
注意Result是阻塞。你也可以awaitReadAsStringAsync()。
回答by Timothy Shields
You can use ReadAsStringAsyncon the Content.
您可以ReadAsStringAsync在Content.
var response = await client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
Note that you usually should be using await- not .Result.
请注意,您通常应该使用await-not .Result。
回答by Niraj Trivedi
You can you ReadAsStringAsync() method
你可以 ReadAsStringAsync() 方法
var result = await response.Content.ReadAsStringAsync();
We need to use await because we are using ReadAsStringAsync() which return task.
我们需要使用 await 因为我们使用的是返回任务的 ReadAsStringAsync()。

