HttpClient 不支持 PostAsJsonAsync 方法 C#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19158378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:15:22  来源:igfitidea点击:

HttpClient not supporting PostAsJsonAsync method C#

c#jsonasp.net-web-apidotnet-httpclient

提问by Jidheesh Rajan

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 HttpClientdoes not contain a definition PostAsJsonAsyncmethod.

我正在尝试从我的 Web 应用程序调用 Web API。我正在使用 .Net 4.5 并且在编写代码时我收到错误HttpClient不包含定义PostAsJsonAsync方法。

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?)

错误:“System.Net.Http.HttpClient”不包含“PostAsJsonAsync”的定义,并且找不到接受“System.Net.Http.HttpClient”类型的第一个参数的扩展方法“PostAsJsonAsync”(您是否缺少使用指令或程序集引用?)

Please have a look and advice me.

请看一看并给我建议。

采纳答案by Justin Harvey

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.Clientto your project.

实现这一目标的一个好方法是将NuGet 包Microsoft.AspNet.WebApi.Client添加到您的项目中。

回答by Todd H.

The missing reference is the System.Net.Http.Formatting.dll. But the better solution is to add the NuGet package Microsoft.AspNet.WebApi.Clientto ensure the version of the formatting dll worked with the .NET framework version of System.Net.Httpin my project.

缺少的参考是System.Net.Http.Formatting.dll. 但更好的解决方案是添加 NuGet 包Microsoft.AspNet.WebApi.Client以确保格式化 dll 的版本与System.Net.Http我的项目中的 .NET 框架版本一起使用。

回答by Andreo Romera

Instead of writing this amount of code to make a simple call, you could use one of the wrappers available over the internet.

您可以使用 Internet 上可用的包装器之一,而不是编写这么多代码来进行简单的调用。

I've written one called WebApiClient, available at NuGet... check it out!

我写了一个名为 WebApiClient 的程序,可在 NuGet 上找到……看看吧!

https://www.nuget.org/packages/WebApiRestService.WebApiClient/

https://www.nuget.org/packages/WebApiRestService.WebApiClient/

回答by Jeroen K

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

PostAsJsonAsync不再在System.Net.Http.dll(.NET 4.5.2) 中。您可以添加对 的引用System.Net.Http.Formatting.dll,但这实际上属于旧版本。我在我们的 TeamCity 构建服务器上遇到了这个问题,这两者不会合作。

Alternatively, you can replace PostAsJsonAsyncwith a PostAsynccall, which is just part of new dll. Replace

或者,您可以替换PostAsJsonAsyncPostAsync调用,它只是新 dll 的一部分。代替

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;

Note that JavaScriptSerializeris in the namespace: System.Web.Script.Serialization.

请注意,JavaScriptSerializer在命名空间中:System.Web.Script.Serialization.

You will have to add an assembly reference in your csproj: System.Web.Extensions.dll

您必须在 csproj 中添加程序集引用: System.Web.Extensions.dll

See https://code.msdn.microsoft.com/windowsapps/How-to-use-HttpClient-to-b9289836

请参阅https://code.msdn.microsoft.com/windowsapps/How-to-use-HttpClient-to-b9289836

回答by Abed Kaff

I know this reply is too late, I had the same issue and i was adding the System.Net.Http.Formatting.ExtensionNuget, after checking here and there I found that the Nuget is added but the System.Net.Http.Formatting.dllwas not added to the references, I just reinstalled the Nuget

我知道这个回复太晚了,我遇到了同样的问题,我正在添加System.Net.Http.Formatting.ExtensionNuget,在这里和那里检查后我发现添加了 Nuget 但System.Net.Http.Formatting.dll没有添加到引用中,我只是重新安装了 Nuget

回答by Christian Gollhardt

As already debatted, this method isn't available anymore since .NET 4.5.2. To expand on Jeroen K's answeryou can make an extension method:

正如已经争论过的,自 .NET 4.5.2 起,此方法不再可用。要扩展Jeroen K 的答案,您可以创建一个扩展方法:

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);
}

Now you are able to call client.PostAsJsonAsync("api/AgentCollection", user).

现在您可以调用client.PostAsJsonAsync("api/AgentCollection", user).

回答by Mr Giggles

I had this issue too on a project I'd just checked out from source control.

我刚刚从源代码管理中检出的项目中也遇到了这个问题。

The symptom was the error described above and a yellow warning triangle on a reference to System.Net.Http.Formatting

症状是上述错误和参考上的黄色警告三角形 System.Net.Http.Formatting

To fix this, I removed the broken reference and then used NuGet to install the latest version of Microsoft.AspNet.WebApi.Client.

为了解决这个问题,我删除了损坏的引用,然后使用 NuGet 安装了最新版本的Microsoft.AspNet.WebApi.Client.

回答by Alexandre Spreafico Novaes

Try to install in your project the NuGet Package: Microsoft.AspNet.WebApi.Client:

尝试在您的项目中安装 NuGet 包:Microsoft.AspNet.WebApi.Client:

Install-Package Microsoft.AspNet.WebApi.Client

回答by Briseis

If you're playing around in Blazor and get the error, you need to add the package Microsoft.AspNetCore.Blazor.HttpClient.

如果您在 Blazor 中玩弄并收到错误,则需要添加 package Microsoft.AspNetCore.Blazor.HttpClient

回答by Click Ok

Just expanding Jeroen's answerwith the tips in comments:

只是用评论中的提示扩展Jeroen 的答案

var content = new StringContent(
    JsonConvert.SerializeObject(user), 
    Encoding.UTF8, 
    MediaTypeNames.Application.Json);

var response = await client.PostAsync("api/AgentCollection", content);