How to read HttpResponseMessage contents as text

I use the HttpResponseMessage class as a response from an AJAX call that returns JSON data from the service. When I pause execution after calling AJAX from a service, I see that this class contains a Content property that is of type System.Net.Http.StreamContent.

If I check in the browser, I see that the network call is successful, and the JSON data as the answer. I'm just wondering why I can't see the returned JSON text from Visual Studio? I searched this System.Net.Http.StreamContent object and did not see any data.

public async Task<HttpResponseMessage> Send(HttpRequestMessage request) { var response = await this.HttpClient.SendAsync(request); return response; } 
+7
json c # asp.net-web-api
source share
2 answers

The textual representation of the response is hidden in the Content property of the HttpResponseMessage class. In particular, you will receive an answer as follows:

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;

Please note that Result blocked. You can also await ReadAsStringAsync() .

+23
source

You can use ReadAsStringAsync in Content .

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

Note that usually you should use await - not .Result .

+5
source

All Articles