132

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.HttpContent' does not contain a definition for 
'ReadAsAsync' and no extension method 'ReadAsAsync' accepting a 
first argument of type 'System.Net.Http.HttpContent' could be 
found (are you missing a using directive or an assembly reference?)

Here's a test method in which this error occurs.

static IEnumerable<Foo> GetAllFoos()
{
  using (HttpClient client = new HttpClient())
  {
    client.DefaultRequestHeaders.Add("appkey", "myapp_key");

    var response = client.GetAsync("http://localhost:57163/api/foo").Result;

    if (response.IsSuccessStatusCode)
      return response.Content.ReadAsAsync<IEnumerable<Foo>>().Result.ToList();
  }

  return null;
}

I have used this method and consumed it from an MVC client.

j0k
  • 22,600
  • 28
  • 79
  • 90
Water Cooler v2
  • 32,724
  • 54
  • 166
  • 336

8 Answers8

164

After a long struggle, I found the solution.

Solution: Add a reference to System.Net.Http.Formatting.dll. This assembly is also available in the C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies folder.

The method ReadAsAsync is an extension method declared in the class HttpContentExtensions, which is in the namespace System.Net.Http in the library System.Net.Http.Formatting.

Reflector came to rescue!

Water Cooler v2
  • 32,724
  • 54
  • 166
  • 336
  • 1
    How did you get that folder there? I used the web platform installer and it didn't make that folder in Program Files. – bladefist Jan 13 '14 at 19:02
  • 7
    Add Reference -> Assemblies -> Extensions. If it is not listed, go to the Search Assemblies box and type 'formatting'. Hopefully that finds it easier for you. – FrankO Oct 13 '14 at 18:19
  • 2
    An update, I found mine here: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Packages\Microsoft.AspNet.WebApi.Client.4.0.30506.0\lib\net40 – PurpleSmurph Sep 25 '17 at 14:51
  • 11
    https://www.nuget.org/packages/System.Net.Http.Formatting.Extension - any reason not to use this? – WernerCD Oct 02 '17 at 22:48
  • 1
    Just install this package `System.Net.Http.Formatting.Extension` from NuGet – Ashique Razak Jan 24 '22 at 05:35
  • The "install nuget package Microsoft.AspNet.WebApi.Client" solution (second most upvoted solution) is more modern -- nowadays it makes more sense than referencing a local assembly. – jeancallisti Jul 01 '22 at 10:51
130

Make sure that you have installed the correct NuGet package in your console application:

<package id="Microsoft.AspNet.WebApi.Client" version="4.0.20710.0" />

and that you are targeting at least .NET 4.0.

This being said, your GetAllFoos function is defined to return an IEnumerable<Prospect> whereas in your ReadAsAsync method you are passing IEnumerable<Foo> which obviously are not compatible types.

Install-Package Microsoft.AspNet.WebApi.Client

Select project in project manager console

Rikin Patel
  • 8,848
  • 7
  • 70
  • 78
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks. That was a slip, a left over from my effort to remove business related code and replace it with Foos. – Water Cooler v2 Jan 25 '13 at 11:41
  • I don't understand. I am already targeting the .NET 4.0 framework in my Console app properties. Do I need to set a reference to this library Microsoft.AspNet.WebAPI.Client.dll? I never set any such reference in the ASP.NET MVC project that also consume my Web API and works just fine. – Water Cooler v2 Jan 25 '13 at 11:46
  • 5
    You need to install the `Microsoft.AspNet.WebApi.Client` NuGet. This will download the latest version from the internet and reference the assembly in your console application. That's exactly what the ASP.NET MVC project template does and is the reason why you don't need to install anything for it to work. But in your console application there's no such thing. – Darin Dimitrov Jan 25 '13 at 11:47
  • 1
    Thanks. I did what you said. I have 12 projects in my solution, but for some strange reason, after I said 'install-package Microsoft.AspNet.WebApi.Client' in the Library Package Manager console, it printed its usual trace and then said 'Successfully installed Microsoft.AspNet.WebApi.Client in MyMVCProjectNameAndNotMyConsoleProjectName'. The next time I selected my Console project and typed the same thing in the package manager console. It said MyMVCProjectName already references Microsoft.AspNet.WebApi.Client. I am confused. – Water Cooler v2 Jan 25 '13 at 12:16
  • Yeah me too. Start from scratch. New console application, open up the NuGet console, type `Install-Package Microsoft.AspNet.WebApi.Client` and try the code. – Darin Dimitrov Jan 25 '13 at 12:20
  • I just did. Still the same situation. No luck. – Water Cooler v2 Jan 25 '13 at 12:44
  • Oh that's very strange. Because I also did that and it worked perfectly fine in a new console application. – Darin Dimitrov Jan 25 '13 at 12:44
  • I am using VS 2010 and targeting .NET Framework 4.0 as the profile. Are these the tools you are using? – Water Cooler v2 Jan 25 '13 at 12:46
  • I am using VS 2012 targeting the full .NET 4.0 profile. Let me try it with VS 2010 as well. – Darin Dimitrov Jan 25 '13 at 12:47
  • Yeah works fine in VS 2010 as well. Even with the .NET 4.0 Client Profile. I suspect that your NuGet system is somehow corrupted and you are not getting the latest version of the `Microsoft.AspNet.WebApi.Client` NuGet from the internet but are using some locally cached version. – Darin Dimitrov Jan 25 '13 at 12:49
  • Would you please take a look at this post on a JSON deserialization problem. http://stackoverflow.com/questions/24131067/deserialize-json-to-array-or-list-with-httpclient-readasasync-using-net-4-0-ta (updated uri) – Joe Jun 10 '14 at 18:09
  • I had to do this in order for the VSTS Build to work. – M Akin Jan 10 '18 at 15:05
  • simply install the Microsoft.AspNet.WebApi.Client reference using Nuget problem get solved. first you shd have the System.Net.Http; reference – Dulakshi Soysa Nov 17 '21 at 14:05
  • Visual Studio 2022 brand new updates. created the API template and run into this issue. This answer solved my problem, installed via nuget. – florian.isopp May 24 '22 at 13:36
37
  • if you unable to find assembly reference from when (Right click on reference ->add required assembly)

try this Package manager console
Install-Package System.Net.Http.Formatting.Extension -Version 5.2.3 and then add by using add reference .

  • 3
    I was migrating dotnetcore application from 2.2 to 3.1 latest and encounter this error.My app already having reference to System.Net.Http.Formatting.Extension v5.2.3 but my app complain this error , so I installed nuget package Microsoft.AspNet.WebApi.Client as suggested by Rikin and Darin and after that issue is resolved. Thanks – AKS Jan 09 '20 at 16:09
15

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:

<dependentAssembly>
   <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
 </dependentAssembly> 

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<T> 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<T>(responseAsString);
         return responseAsConcreteType;
      }
}
Conor Kelly
  • 261
  • 3
  • 8
9

or if you have VS 2012 you can goto the package manager console and type Install-Package Microsoft.AspNet.WebApi.Client

This would download the latest version of the package

Ram
  • 91
  • 1
  • 1
4

Install below package from nuget enter image description here

Hisham Shahid
  • 225
  • 3
  • 7
3

Had the same issue, but proposed answers didn't help, installing System.Net.Http.Json package removed the error.

Natalija
  • 31
  • 2
-1

USE This Assembly Referance in your Project

Add a reference to System.Net.Http.Formatting.dll
Debendra Dash
  • 5,334
  • 46
  • 38
  • 7
    The accepted answer from January 2013 already explains this and has more information. Your answer is also not properly formatted. – user247702 Nov 08 '16 at 12:29