Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...