我正在使用 Microsoft.AspNet.WebApi.Client在我的 ASP.MVC 5 项目中使用休息服务。我正在关注 this使用 HttpClient 的教程。代码未编译,因为 ReadAsAsync
方法在 HttpContent 中不再可用。经过一番挖掘后,我开始知道它是 System.Net.Http.Formatting.dll
中定义的扩展方法。我为同一个 dll 找到了一个 nuget 包 here但该软件包已被弃用,我无法安装它。我还尝试根据 this 在 Program Files 文件夹中搜索该 dll。发布但我无法得到它。任何想法如何使 ReadAsAsync
工作?非常感谢任何帮助。谢谢。
最佳答案
您需要做的是添加新的引用 System.Net.HttpClient;
和 System.Net.HttpClient.Formating;
。
这是我在 HttpClient 中的示例代码:
以下代码用于使用 HttpClient 从 saba 获取证书。
using System.Net.Http;
using System.Net.Http.Headers;
using GoSaba.Models.Saba;
namespace GoSaba.Controllers.Saba
{
class LoginController
{
//HTTP GET: Saba/api/login
public async Task<string> GetCertificate(string host, string user, string password, string site)
{
StringBuilder getCertificate = new StringBuilder();
if(!string.IsNullOrEmpty(host))
{
using(var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(string.Format("http://{0}/", host));
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Add("user", user);
httpClient.DefaultRequestHeaders.Add("password", password);
httpClient.DefaultRequestHeaders.Add("site", site);
HttpResponseMessage httpResponse = await httpClient.GetAsync("Saba/api/login");
if(httpResponse.IsSuccessStatusCode)
{
LoginModel.GetCertificate saba = await httpResponse.Content.ReadAsAsync<LoginModel.GetCertificate>();//LoginModel.GetCertificate is model.
getCertificate.Append(saba.certificate);
}
}
}
return getCertificate.ToString();
}
}
}
您可以将此作为如何使用 HttpClient 的引用。
关于c# - HttpContent 中 ReadAsAsync 方法的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26624484/