c# - 缺少 HttpClient 对象方法

标签 c#

我正在从网站中分离出一些代码,并在复制相关特定页面的代码后,我在 PostAsJsonAsync() 代码行中遇到错误:

HttpResponseMessage response = await client.PostAsJsonAsync("api/...", user);

在这个 using 语句中(也添加了标题)

        using System;
        using System.Net.Http;
        using System.Net.Http.Headers;
        using System.Net.Mail;
        using System.Threading.Tasks;
        //...

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("WebServiceAddress");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.PostAsJsonAsync("api/...", user);
            if (response.IsSuccessStatusCode)
            {
                const string result = "Thank you for your submission.";
                return result;
            }
            //...
        }

我得到的错误是

 Error  4   '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

它应该在 extensions -> assembly 中。

您可以添加Microsoft.AspNet.WebApi.Client nuget包

关于c# - 缺少 HttpClient 对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29923979/

相关文章:

c# - 带有 Entity Framework 的 MVC 3 和编辑多个对象导致 "referential integrity constraint violation"

c# - 在反射(reflect)的导航属性上添加排序

c# - 如何在 C# UWP 中从 Azure 移动应用程序读取数据

c# - 从网络驱动器连接/复制

c# - 为我的自定义用户控件创建自定义工具箱图标

c# - .NET Form close/dispose 不释放全局对象

c# - 从查询字符串开始时比较 EntitySQL 中的 DateTime 值

c# - 当自动调整大小打开时,获取 ListView 中列的实际宽度

c# - 将 C# 7 代码部署到 VSTS

c# - 访问IsolatedStorageBackingStore时出现HRESULT 0X80131468的原因