HttpClient 不支持 PostAsJsonAsync 方法 C# [英] HttpClient not supporting PostAsJsonAsync method C#
问题描述
我正在尝试从我的 Web 应用程序调用 Web API.我正在使用 .Net 4.5,在编写代码时出现错误 HttpClient
不包含定义 PostAsJsonAsync
方法.
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.
代码如下:
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;
我收到错误消息:
错误:System.Net.Http.HttpClient"不包含定义PostAsJsonAsync"和无扩展方法PostAsJsonAsync"接受第一个参数可以找到类型System.Net.Http.HttpClient"(您是否缺少using 指令或程序集引用?)
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?)
请看一看并给我建议.
推荐答案
是的,需要添加对
System.Net.Http.Formatting.dll
这可以在扩展程序集区域中找到.
This can be found in the extensions assemblies area.
实现这一点的一个好方法是添加 NuGet 包 Microsoft.AspNet.WebApi.Client
到您的项目.
A good way of achieving this is by adding the NuGet package Microsoft.AspNet.WebApi.Client
to your project.
这篇关于HttpClient 不支持 PostAsJsonAsync 方法 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!