Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c# - 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. 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.

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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;

Note that Result is blocking. You can also await ReadAsStringAsync().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...