'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

后端 未结 6 2168
梦如初夏
梦如初夏 2020-12-02 16:27

I made a console app to consume a Web API I just made. The console app code does not compile. It gives me the compilation error:

\'System.Net.Http.HttpConten         


        
6条回答
  •  眼角桃花
    2020-12-02 16:58

    Adding a reference to System.Net.Http.Formatting.dll may cause DLL mismatch issues. Right now, System.Net.Http.Formatting.dll appears to reference version 4.5.0.0 of Newtonsoft.Json.DLL, whereas the latest version is 6.0.0.0. That means you'll need to also add a binding redirect to avoid a .NET Assembly exception if you reference the latest Newtonsoft NuGet package or DLL:

    
       
        
      
    

    So an alternative solution to adding a reference to System.Net.Http.Formatting.dll is to read the response as a string and then desearalize yourself with JsonConvert.DeserializeObject(responseAsString). The full method would be:

    public async Task GetHttpResponseContentAsType(string baseUrl, string subUrl)
    {
         using (var client = new HttpClient())
         {
             client.BaseAddress = new Uri(baseUrl);
             client.DefaultRequestHeaders.Accept.Clear();
             client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
             HttpResponseMessage response = await client.GetAsync(subUrl);
             response.EnsureSuccessStatusCode();
             var responseAsString = await response.Content.ReadAsStringAsync();
             var responseAsConcreteType = JsonConvert.DeserializeObject(responseAsString);
             return responseAsConcreteType;
          }
    }
    

提交回复
热议问题