我正在从网站中分离出一些代码,并在复制相关特定页面的代码后,我在 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/