我正在尝试从我的Web应用程序调用Web API。我正在使用.Net 4.5,在编写代码时,我收到的错误HttpClient
不包含定义PostAsJsonAsync
方法。
以下是代码:
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指令或程序集引用?)
请看一下并给我建议。
答案 0 :(得分:344)
是的,您需要添加对
的引用System.Net.Http.Formatting.dll
这可以在扩展程序集区域中找到。
实现这一目标的一个好方法是将NuGet包System.Net.Http.Formatting.Extension
添加到您的项目中。
答案 1 :(得分:154)
缺少的参考是System.Net.Http.Formatting.dll
。但更好的解决方案是添加NuGet包Microsoft.AspNet.WebApi.Client
以确保格式化dll的版本与我项目中的System.Net.Http
的.NET框架版本一起使用。
答案 2 :(得分:153)
System.Net.Http.dll
不再位于System.Net.Http.Formatting.dll
(.NET 4.5.2)中。您可以添加对PostAsJsonAsync
的引用,但这实际上属于旧版本。我在TeamCity构建服务器上遇到了这个问题,这两个不会合作。
或者,您可以将PostAsync
替换为var response = client.PostAsJsonAsync("api/AgentCollection", user).Result;
来电,这只是新dll的一部分。
取代
var response = client.PostAsync("api/AgentCollection", new StringContent(
new JavaScriptSerializer().Serialize(user), Encoding.UTF8, "application/json")).Result;
使用:
* Virtual Guest:
https://[username]:[apikey]@api.softlayer.com/rest/v3/SoftLayer_Virtual_Guest/[vsi_id]/getObject?objectMask=mask[id,fullyQualifiedDomainName,billingItem[id,orderItem[id,description,order[id,items]]]]
* Hardware:
https://[username]:[apikey]@api.softlayer.com/rest/v3/SoftLayer_Hardware/[hardware_id]/getObject?objectMask=mask[id,fullyQualifiedDomainName,billingItem[id,orderItem[id,description,order[id,items]]]]
请参阅https://code.msdn.microsoft.com/windowsapps/How-to-use-HttpClient-to-b9289836
答案 3 :(得分:30)
如前所述,自.NET 4.5.2起,此方法不再可用。要展开Jeroen K's answer,您可以制作扩展方法:
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);
}
现在您可以致电client.PostAsJsonAsync("api/AgentCollection", user)
。
答案 4 :(得分:10)
我刚刚从源代码管理中检出的项目也遇到了这个问题。
症状是上述错误和System.Net.Http.Formatting
要解决此问题,我删除了损坏的引用,然后使用NuGet安装最新版本的Microsoft.AspNet.WebApi.Client
。
答案 5 :(得分:3)
我知道这个回复为时已晚,我遇到了同样的问题而我正在添加a = [("apple", "mango"), "orange"] # This is [tuple, str]
b = ["grapes", ("pineapple", "lemon")] # This one's [str, tuple]
flatten = ( lambda itr: sum(map(flatten, itr), tuple())
if isinstance(itr, tuple) else (itr,)
)
c = [flatten(x) for x in zip(a, b)]
print (c)
# [('apple', 'mango', 'grapes'), ('orange', 'pineapple', 'lemon')]
Nuget,在此处检查后我发现添加了Nuget但未添加"" opens original file instead of symlink
autocmd BufEnter * if getftype(expand("%")) == 'link' | execute 'file '.system('readlink '.expand('%')) | endif
对于参考文献,我刚刚重新安装了Nuget
答案 6 :(得分:3)
好的,现在是世界末日2020年,您可以在NuGet软件包System.Net.Http.Json
中找到这些方法。但是请注意,它在内部使用System.Text.Json
。
如果您真的需要找出哪个API驻留在哪里,只需使用https://apisof.net/
答案 7 :(得分:2)
您可以使用互联网上提供的其中一个包装器,而不是编写这么多代码来进行简单的调用。
我写了一篇名为WebApiClient的文章,可以在NuGet上找到...看看吧!
https://www.nuget.org/packages/WebApiRestService.WebApiClient/
答案 8 :(得分:1)
如果你已经在使用 Newtonsoft.Json,试试这个:
// 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"));
性能优于 JavaScriptSerializer。看看这里https://www.newtonsoft.com/json/help/html/Introduction.htm
答案 9 :(得分:0)
尝试在您的项目中安装NuGet软件包:Microsoft.AspNet.WebApi.Client:
Install-Package Microsoft.AspNet.WebApi.Client
答案 10 :(得分:0)
如果您在Blazor中玩耍并遇到错误,则需要添加软件包Microsoft.AspNetCore.Blazor.HttpClient
。
答案 11 :(得分:0)
使用注释中的提示扩展Jeroen's answer:
var content = new StringContent(
JsonConvert.SerializeObject(user),
Encoding.UTF8,
MediaTypeNames.Application.Json);
var response = await client.PostAsync("api/AgentCollection", content);
答案 12 :(得分:0)
对我来说,经过多次尝试,我找到了解决方案
HttpClient
使用
System.Net.Http.HttpClient