HttpClient not supporting PostAsJsonAsync method C#
I am trying to call a web api from my web application.Am using .net 4.5 and while writing the code i am getting an error HttpClient does not contain a definition PostAsJsonAsync method
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.
Yes, you need to add a reference to
System.Net.Http.Formatting.dll
This can be found in the extensions assemblies area.
Note that a good way of achieving this is by adding the NuGet package System.Net.Http.Formatting.Extension
to your project.
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.
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 PostAsJsonAsync
with 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;
See https://code.msdn.microsoft.com/windowsapps/How-to-use-HttpClient-to-b9289836
链接地址: http://www.djcxy.com/p/45870.html