I’m trying to use my web application to call a web API. I’m using.Net 4.5 and getting the error HttpClient does not contain a definition PostAsJsonAsync method while writing the code.
The code is as follows:
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;
I’m getting the following error message:
Please have a look and give me some advice.
Asked by Jidheesh Rajan
Yes, a reference to is required.
This can be found in the extensions assemblies area.
Adding the NuGet package Microsoft.AspNet.WebApi.Client to your project is a nice method to accomplish this.
Answered by Justin Harvey
System.Net.Http.dll no longer contains PostAsJsonAsync (.NET 4.5.2). A reference to System.Net.Http.Formatting.dll can be included, although this is from an older version. On our TeamCity build server, I had issues with this because these two wouldn’t work together.
You can also use a PostAsync call instead of PostAsJsonAsync, which is included in the new dll. Replace
var response = client.PostAsJsonAsync("api/AgentCollection", user).Result;
You’ll need to include System.Web.Extensions.dll as an assembly reference in your csproj.
Answered by Jeroen K
System.Net.Http.Formatting.dll is the missing reference. However, adding the NuGet package Microsoft.AspNet.WebApi.Client to my project ensured that the version of the formatting dll in my project worked with the.NET framework version of System.Net.Http.
Answered by Todd H.
As previously stated, this approach is no longer available as of.NET 4.5.2. You can make an extension method based on Jeroen K’s response:
You can now call the client. “api/AgentCollection”, “user”, PostAsJsonAsync(“api/AgentCollection”, “api/AgentCollection”, “api/AgentCollection”, “api/
Answered by Christian Gollhardt
On a project I’d just checked out from source control, I encountered the same problem.
The error indicated above, as well as a yellow warning triangle on a reference to System.Net.Http.Formatting, were the symptoms.
To remedy this, I removed the faulty reference and then installed the most recent version of Microsoft using NuGet. AspNet.WebApi.Client.
Answered by Mr Giggles
Post is based on https://stackoverflow.com/questions/19158378/httpclient-not-supporting-postasjsonasync-method-c-sharp