Where is HttpContent.ReadAsAsync?

后端 未结 6 1121

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

相关标签:
6条回答
  • 2020-11-29 17:51

    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);
    
    0 讨论(0)
  • 2020-11-29 17:52

    It looks like it is an extension method (in System.Net.Http.Formatting):

    HttpContentExtensions Class

    Update:

    PM> install-package Microsoft.AspNet.WebApi.Client

    According to the System.Net.Http.Formatting NuGet package page, the System.Net.Http.Formatting package is now legacy and can instead be found in the Microsoft.AspNet.WebApi.Client package available on NuGet here.

    0 讨论(0)
  • 2020-11-29 17:58

    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.

    0 讨论(0)
  • 2020-11-29 18:12

    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());
    }
    
    0 讨论(0)
  • 2020-11-29 18:13

    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());
    
    0 讨论(0)
  • 2020-11-29 18:13

    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

    0 讨论(0)
提交回复
热议问题