HttpClient not supporting PostAsJsonAsync method C#

316,985

Solution 1

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.

Solution 2

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

Solution 3

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.

Solution 4

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).

Solution 5

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.

Share:
316,985

Related videos on Youtube

Jidheesh Rajan
Author by

Jidheesh Rajan

.Net Programmer

Updated on February 13, 2021

Comments

  • Jidheesh Rajan
    Jidheesh Rajan over 3 years

    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.

    • Sachin Pawar
      Sachin Pawar almost 8 years
      The best option is to add 'Microsoft.AspNet.WebApi.Client' .Nuget package. That's it!
  • Jidheesh Rajan
    Jidheesh Rajan over 10 years
    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. "
  • Allan Elder
    Allan Elder over 10 years
    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 james.newtonking.com/json
  • vikingben
    vikingben over 10 years
    Here is the console command if anyone is looking nuget.org/packages/System.Net.Http.Formatting
  • Todd H.
    Todd H. almost 10 years
    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.
    Todd H. almost 10 years
    @Yuval - I realize now that the "solution" I suggested sounded like a comment. It turns out that Andreo authored the NuGet package I suggested.
  • Neutrino
    Neutrino over 9 years
    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!
  • reggaeguitar
    reggaeguitar almost 9 years
    @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
  • sasha.sochka
    sasha.sochka over 8 years
    is there a way to use this method from UWP app?
  • Alireza
    Alireza over 8 years
    This should be the answer. The best way to do something is the correct way of it
  • Gökhan Kurt
    Gökhan Kurt over 8 years
    This is the best answer so far. Do not try adding NuGet packages or dlls.
  • Yar
    Yar about 8 years
    PM> Install-Package System.Net.Http.Formatting.Extension
  • Astaar
    Astaar almost 8 years
    Totally the best answer. Selected answer is not a best practice at all, in fact Microsoft recommends not to reference DLLs
  • RasikaSam
    RasikaSam over 7 years
    This was the answer to me! (to my question)
  • flexxxit
    flexxxit about 7 years
    how will this be added in .net4
  • Vishwajit G
    Vishwajit G over 6 years
    @Andreo The link (webapiclient.azurewebsites.net) is now broken as on 30-Nov-2017. NuGet working link is nuget.org/packages/WebApiRestService.WebApiClient
  • yu yang Jian
    yu yang Jian over 6 years
    It works! To install by Nuget Console enter Install-Package Microsoft.AspNet.WebApi.Client
  • Andreo Romera
    Andreo Romera about 6 years
    Unfortunately Microsoft has ended my azure subscription and the url is no longer valid :(
  • Zin Min
    Zin Min about 6 years
    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
  • Thomas Schreiter
    Thomas Schreiter almost 6 years
    Off topic, but I want to mention it anyways: Use await FooAsync() instead of FooAsync().Result. The latter one can deadlock. See stackoverflow.com/q/17248680/2272514 and its accepted answer. There are also good links about details.
  • daviesdoesit
    daviesdoesit over 5 years
    To use a type instead of "application/json" you could use MediaTypeNames.Application.Json docs.microsoft.com/en-us/dotnet/api/…
  • tmutton
    tmutton almost 5 years
    This helped me and is obviously preferable to installing a library via nuget. Thank you.
  • Yusha
    Yusha almost 5 years
    What the answer should actually say. Nuget > Install System.Net.Http then install System.Net.Http.Formatting.Extension
  • Cameron Forward
    Cameron Forward almost 5 years
    Worked a charm - I successfully used JsonConvert.SerializeObject(user) in place of your serialiser.
  • Ryanman
    Ryanman almost 5 years
    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.
  • goodeye
    goodeye almost 5 years
    Great - I used this for the general idea when debugging some json from .net core 2.2. From this post 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)
  • Benj Sanders
    Benj Sanders over 4 years
    @Yusha I needed to add Microsoft.AspNet.WebApi.Client and System.Net.Http.Formatting.Extension, then it compiled.
  • rfcdejong
    rfcdejong over 3 years
    Works for me for .net framework and netcore3.1 (which uses netstandard2.0 in this library)
  • rfcdejong
    rfcdejong over 3 years
  • SomeoneElse
    SomeoneElse over 2 years
    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.