Coder Perfect

Where is HttpContent.ReadAsAsync?

Problem

I notice HttpContent.ReadAsAsyncT> function in a lot of examples on the web using the new HttpClient object (as part of the new Web API). This technique isn’t mentioned in MSDN, and IntelliSense doesn’t locate it either.

What happened to it, and how can I get it back?

Asked by David Pfeffer

Solution #1

It appears to be a System.Net.Http.Formatting extension method:

HttpContentExtensions Class

Update:

According to the System.Net.Http.Formatting NuGet package page, the System.Net.Http.Formatting package is now deprecated and should be replaced with the Microsoft.AspNet.WebApi.Client product, which can be found on NuGet here.

Answered by J…

Solution #2

I have the same problem, so I simply get JSON string and deserialize to my class:

HttpResponseMessage response = await client.GetAsync("Products");
//get data as Json string 
string data = await response.Content.ReadAsStringAsync();
//use JavaScriptSerializer from System.Web.Script.Serialization
JavaScriptSerializer JSserializer = new JavaScriptSerializer();
//deserialize to your class
products = JSserializer.Deserialize<List<Product>>(data);

Answered by rosta

Solution #3

If you don’t want to install Microsoft.AspNet.WebApi.Client because you already have Newtonsoft.Json installed:

 var myInstance = JsonConvert.DeserializeObject<MyClass>(
   await response.Content.ReadAsStringAsync());

Answered by Martin Brandl

Solution #4

You can use the following syntax to write an extension method:

public static async Task<Tout> ReadAsAsync<Tout>(this System.Net.Http.HttpContent content) {
    return Newtonsoft.Json.JsonConvert.DeserializeObject<Tout>(await content.ReadAsStringAsync());
}

Answered by Vasya Milovidov

Solution #5

Update for 2021: The function appears to be deprecated in.NET5. ReadFromJsonAsync>() from System.Net.Http.Json.HttpContentJsonExtensions is another option. It accomplishes the goal.

Answered by Mangesh

Post is based on https://stackoverflow.com/questions/10399324/where-is-httpcontent-readasasync