[c#] HttpClient not supporting PostAsJsonAsync method C#

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.

This question is related to c# json asp.net-web-api dotnet-httpclient

The answer is


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.


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

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


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/


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


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


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

Install-Package Microsoft.AspNet.WebApi.Client

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.


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

HttpClient

with

System.Net.Http.HttpClient

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/


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


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


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to asp.net-web-api

Entity Framework Core: A second operation started on this context before a previous operation completed FromBody string parameter is giving null How to read request body in an asp.net core webapi controller? JWT authentication for ASP.NET Web API Token based authentication in Web API without any user interface Web API optional parameters How do I get the raw request body from the Request.Content object using .net 4 api endpoint How to use a client certificate to authenticate and authorize in a Web API HTTP 415 unsupported media type error when calling Web API 2 endpoint The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

Examples related to dotnet-httpclient

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body? Custom header to HttpClient request Adding headers when using httpClient.GetAsync HttpClient - A task was cancelled? How to get content body from a httpclient call? Pass multiple complex objects to a post/put Web API method Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern Why is HttpClient BaseAddress not working? Make Https call using HttpClient Deciding between HttpClient and WebClient