I see in tons of examples on the web using the new HttpClient
object (as part of the new Web API) that there should be HttpContent.ReadAsAsync<T>
method. However, MSDN doesn't mention this method, nor does IntelliSense find it.
Where did it go, and how do I work around it?
This question is related to
c#
.net
asp.net-web-api
httpcontent
If you are already using Newtonsoft.Json
and don't want to install Microsoft.AspNet.WebApi.Client
:
var myInstance = JsonConvert.DeserializeObject<MyClass>(
await response.Content.ReadAsStringAsync());
You can write extention method:
public static async Task<Tout> ReadAsAsync<Tout>(this System.Net.Http.HttpContent content) {
return Newtonsoft.Json.JsonConvert.DeserializeObject<Tout>(await content.ReadAsStringAsync());
}
Having hit this one a few times and followed a bunch of suggestions, if you don't find it available after installing the NuGet Microsoft.AspNet.WebApi.Client manually add a reference from the packages folder in the solution to:
\Microsoft.AspNet.WebApi.Client.5.2.6\lib\net45\System.Net.Http.Formatting.dll
And don't get into the trap of adding older references to the System.Net.Http.Formatting.dll NuGet
Just right click in your project go Manage NuGet Packages search for Microsoft.AspNet.WebApi.Client install it and you will have access to the extension method.
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);
Source: Stackoverflow.com