318

I am trying to call a web API from my web application. I am using .Net 4.5 and while writing the code I am getting the error HttpClient does not contain a definition PostAsJsonAsync method.

Below is the code:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:51093/");
client.DefaultRequestHeaders.Accept.Add(
   new MediaTypeWithQualityHeaderValue("application/json"));
var user = new Users();
user.AgentCode = 100;
user.Remarks = "Test";
user.CollectionDate = System.DateTime.Today;
user.RemittanceDate = System.DateTime.Today;
user.TotalAmount = 1000;
user.OrgBranchID = 101;

var response = client.PostAsJsonAsync("api/AgentCollection", user).Result;

and I am getting the error message:

Error: 'System.Net.Http.HttpClient' does not contain a definition for 'PostAsJsonAsync' and No extension method 'PostAsJsonAsync' accepting a first argument of type 'System.Net.Http.HttpClient' could be found (are you missing a using directive or an assembly reference?)

Please have a look and advice me.

Ferdipux
  • 5,116
  • 1
  • 19
  • 33
Jidheesh Rajan
  • 4,744
  • 4
  • 23
  • 29

15 Answers15

542

Yes, you need to add a reference to

System.Net.Http.Formatting.dll

This can be found in the extensions assemblies area.

A good way of achieving this is by adding the NuGet package Microsoft.AspNet.WebApi.Client to your project.

Amirhossein Mehrvarzi
  • 18,024
  • 7
  • 45
  • 70
Justin Harvey
  • 14,446
  • 2
  • 27
  • 30
  • 7
    Now i am getting an error :" Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified. " – Jidheesh Rajan Oct 03 '13 at 12:20
  • 2
    Go into NuGet and look up Json.NET under online packages, or you can download from here if you aren't using NuGet get it from here http://james.newtonking.com/json – Allan Elder Oct 03 '13 at 13:04
  • Here is the console command if anyone is looking http://www.nuget.org/packages/System.Net.Http.Formatting – vikingben Jan 28 '14 at 23:19
  • 93
    Found I had to add the NuGet package "Microsoft.AspNet.WebApi.Client" to ensure the version of the formatting dll worked with the .NET framework version of "System.Net.Http" in my project. – Todd H. Jun 14 '14 at 06:10
  • 34
    Why does referencing a standard system assembly require me to download open source stuff from random locations on the Internet in order to get it to function? Why does this even compile if it cannot resolve its dependencies? This irks me to no end! – Neutrino Oct 01 '14 at 14:38
  • 4
    @Neutrino Would you rather write the code yourself? You should be thankful that the folks at Microsoft and elsewhere have written code you can use for free – reggaeguitar Jun 09 '15 at 22:41
  • is there a way to use this method from UWP app? – sasha.sochka Nov 08 '15 at 04:02
  • 6
    PM> Install-Package System.Net.Http.Formatting.Extension – Yar Mar 21 '16 at 15:18
  • how will this be added in .net4 – flexxxit Feb 27 '17 at 10:10
  • After I added System.Net.Http.Formatting.Extension from NuGet, HttpClient was thrown an error. Now I am finding the root cause. Visual Studio 2017 with .NET Framework 4.7 – Zin Min Apr 27 '18 at 10:45
  • 1
    What the answer should *actually say*. *Nuget > Install System.Net.Http* then install *System.Net.Http.Formatting.Extension* – Yusha Jun 12 '19 at 19:40
  • 1
    @Yusha I needed to add Microsoft.AspNet.WebApi.Client and System.Net.Http.Formatting.Extension, then it compiled. – Benj Sanders Oct 25 '19 at 21:53
  • 2020 answer -> https://stackoverflow.com/a/64015973/578552 – rfcdejong Sep 30 '20 at 13:57
236

PostAsJsonAsync is no longer in the System.Net.Http.dll (.NET 4.5.2). You can add a reference to System.Net.Http.Formatting.dll, but this actually belongs to an older version. I ran into problems with this on our TeamCity build server, these two wouldn't cooperate together.

Alternatively, you can replace PostAsJsonAsyncwith a PostAsync call, which is just part of new dll. Replace

var response = client.PostAsJsonAsync("api/AgentCollection", user).Result;

With:

var response = client.PostAsync("api/AgentCollection", new StringContent(
   new JavaScriptSerializer().Serialize(user), Encoding.UTF8, "application/json")).Result;

Note that JavaScriptSerializer is in the namespace: System.Web.Script.Serialization.

You will have to add an assembly reference in your csproj: System.Web.Extensions.dll

See https://code.msdn.microsoft.com/windowsapps/How-to-use-HttpClient-to-b9289836

Ambrose Leung
  • 3,704
  • 2
  • 25
  • 36
Jeroen K
  • 10,258
  • 5
  • 41
  • 40
  • 9
    This should be the answer. The best way to do something is the correct way of it – Alireza Jan 28 '16 at 00:56
  • 6
    This is the best answer so far. Do not try adding NuGet packages or dlls. – Gökhan Kurt Jan 29 '16 at 15:02
  • 5
    Totally the best answer. Selected answer is not a best practice _at all_, in fact Microsoft recommends not to reference DLLs – Astaar Jul 29 '16 at 09:35
  • 6
    Off topic, but I want to mention it anyways: Use `await FooAsync()` instead of `FooAsync().Result`. The latter one can deadlock. See https://stackoverflow.com/q/17248680/2272514 and its accepted answer. There are also good links about details. – Thomas Schreiter Jul 31 '18 at 23:58
  • 3
    To use a type instead of "application/json" you could use MediaTypeNames.Application.Json https://learn.microsoft.com/en-us/dotnet/api/system.net.mime.mediatypenames.application.json?view=netcore-2.2 – daviesdoesit Jan 07 '19 at 19:20
  • This helped me and is obviously preferable to installing a library via nuget. Thank you. – tmutton May 29 '19 at 16:29
  • 2
    Worked a charm - I successfully used JsonConvert.SerializeObject(user) in place of your serialiser. – Cameron Forward Jun 25 '19 at 04:54
  • This is the second time I've forgotten this answer. PostAsJsonAsync will mysteriously exclude properties from the object you're posting when serializing etc. and no amount of attribute changes etc. will fix it. You MUST serialize yourself and you MUST use the "raw" PostAsync. – Ryanman Jul 25 '19 at 19:46
  • Great - I used this for the general idea when debugging some json from .net core 2.2. From this post https://stackoverflow.com/a/29843542/292060 it shows using existing Newtonsoft library to serialize (even though the post is about how that's being removed from core 3.0) – goodeye Jul 27 '19 at 22:59
169

The missing reference is the System.Net.Http.Formatting.dll. But the better solution is to add the NuGet package Microsoft.AspNet.WebApi.Client to ensure the version of the formatting dll worked with the .NET framework version of System.Net.Http in my project.

burnttoast11
  • 1,164
  • 16
  • 33
Todd H.
  • 2,522
  • 1
  • 18
  • 9
41

As already debatted, this method isn't available anymore since .NET 4.5.2. To expand on Jeroen K's answer you can make an extension method:

public static async Task<HttpResponseMessage> PostAsJsonAsync<TModel>(this HttpClient client, string requestUrl, TModel model)
{
    var serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(model);
    var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
    return await client.PostAsync(requestUrl, stringContent);
}

Now you are able to call client.PostAsJsonAsync("api/AgentCollection", user).

Community
  • 1
  • 1
Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111
13

I had this issue too on a project I'd just checked out from source control.

The symptom was the error described above and a yellow warning triangle on a reference to System.Net.Http.Formatting

To fix this, I removed the broken reference and then used NuGet to install the latest version of Microsoft.AspNet.WebApi.Client.

Mr Giggles
  • 2,483
  • 3
  • 22
  • 35
5

I know this reply is too late, I had the same issue and i was adding the System.Net.Http.Formatting.Extension Nuget, after checking here and there I found that the Nuget is added but the System.Net.Http.Formatting.dll was not added to the references, I just reinstalled the Nuget

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
Abed Kaff
  • 61
  • 1
  • 4
5

Try to install in your project the NuGet Package: Microsoft.AspNet.WebApi.Client:

Install-Package Microsoft.AspNet.WebApi.Client
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
5

Ok, it is apocalyptical 2020 now, and you can find these methods in NuGet package System.Net.Http.Json. But beware that it uses System.Text.Json internally.

And if you really need to find out which API resides where, just use https://apisof.net/

Pavel Voronin
  • 13,503
  • 7
  • 71
  • 137
5

If you are already using Newtonsoft.Json try this:

  // Alternative using WebApi.Client 5.2.7
  ////var response = await Client.PutAsJsonAsync(
  ////    "api/AgentCollection", user
  ////    requestListDto)

  var response = await Client.PostAsync("api/AgentCollection", new StringContent(
    JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json"));

Performance are better than JavaScriptSerializer. Take a look here https://www.newtonsoft.com/json/help/html/Introduction.htm

Andrea86
  • 129
  • 1
  • 8
2

Instead of writing this amount of code to make a simple call, you could use one of the wrappers available over the internet.

I've written one called WebApiClient, available at NuGet... check it out!

https://www.nuget.org/packages/WebApiRestService.WebApiClient/

  • [@Andreo](https://stackoverflow.com/users/3738778/andreo-romera) The link (http://webapiclient.azurewebsites.net) is now broken as on 30-Nov-2017. NuGet working link is https://www.nuget.org/packages/WebApiRestService.WebApiClient/ – Vishwajit G Nov 30 '17 at 06:09
  • Unfortunately Microsoft has ended my azure subscription and the url is no longer valid :( – Andreo Romera Mar 06 '18 at 18:38
  • Actually, this is a really good demonstration of why using "one of the wrappers available over the internet" might not be a good idea. Every external dependency that a project has is one more thing that can go wrong. – SomeoneElse Oct 21 '21 at 19:42
2

If you're playing around in Blazor and get the error, you need to add the package Microsoft.AspNetCore.Blazor.HttpClient.

Kevin
  • 16,549
  • 8
  • 60
  • 74
Briseis
  • 43
  • 1
  • 6
0

Just expanding Jeroen's answer with the tips in comments:

var content = new StringContent(
    JsonConvert.SerializeObject(user), 
    Encoding.UTF8, 
    MediaTypeNames.Application.Json);

var response = await client.PostAsync("api/AgentCollection", content);
Click Ok
  • 8,700
  • 18
  • 70
  • 106
0

For me I found the solution after a lot of try which is replacing

HttpClient

with

System.Net.Http.HttpClient
0

If you are using Blazor components and getting this error that means your component is not able to find the http client. use this line on top on your blazor component.

@inject HttpClient Http

Make sure you have this line in your Program or startup file

builder.Services.AddScoped(sp => 
new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

Prince
  • 103
  • 1
  • 6
0

Based on the answers here talking about using Newtonsoft.Json, I created a helper class for this:

public class JsonContent : StringContent
{
    public JsonContent(object model) 
        : base(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json")
    {
    }
}

Example usage:

using (var content = new JsonContent(user))
{
    var response = client.PostAsync("api/AgentCollection", content).Result;
}
kevinpo
  • 1,853
  • 19
  • 20