简体   繁体   English

如何将 HttpResponseMessage 内容读取为文本

[英]How to read HttpResponseMessage content as text

I'm using HttpResponseMessage class as a response from an AJAX call which is returning JSON data from a service.我使用 HttpResponseMessage 类作为 AJAX 调用的响应,该调用从服务返回 JSON 数据。 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.当我在 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.如果我在浏览器中检查,我会看到网络调用成功进行,并且 JSON 数据作为响应。 I'm just wondering why I cannot see the returned JSON text from within Visual Studio?我只是想知道为什么我在 Visual Studio 中看不到返回的 JSON 文本? I searched throughout this System.Net.Http.StreamContent object and see no data.我搜索了整个 System.Net.Http.StreamContent 对象,但没有看到任何数据。

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.响应的文本表示隐藏在HttpResponseMessage类的Content属性中。 Specifically, you get the response like this:具体来说,您会得到如下响应:

response.Content.ReadAsStringAsync();

Like all modern Async methods, ReadAsStringAsync returns a Task .像所有现代Async方法一样, ReadAsStringAsync返回一个Task To get the result directly, use the Result property of the task:要直接获取结果,请使用任务的Result属性:

response.Content.ReadAsStringAsync().Result;

Note that Result is blocking.请注意, Result是阻塞的。 You can also await ReadAsStringAsync() .您也可以await ReadAsStringAsync()

You can use ReadAsStringAsync on the Content .您可以在Content上使用ReadAsStringAsync

var response = await client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();

Note that you usually should be using await - not .Result .请注意,您通常应该使用await - 而不是.Result

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()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM