[英]How to use HttpClient in ASP.NET Core app
I am trying to build an app with ASP.NET Core (aka vNext). 我正在尝试使用ASP.NET Core(aka vNext)构建一个应用程序。 I need to call a third-party REST-API. 我需要调用第三方REST-API。 Traditionally, I would use HttpClient. 传统上,我会使用HttpClient。 However, I can't seem to get it to work. 但是,我似乎无法让它发挥作用。 In my project.json file I have: 在我的project.json文件中,我有:
"dependencies": {
"Microsoft.Net.Http.Client": "1.0.0-*"
}
When I run dnu restore
, I receive an error that says: "Unable to locate Microsoft.Net.Http.Client >= 1.0.0-*". 当我运行dnu restore
,我收到一条错误消息:“无法找到Microsoft.Net.Http.Client> = 1.0.0- *”。 The other post referred to by the commenter is out-of-date. 评论者提到的另一篇文章已经过时了。
I am building this app in Mac OS X. I don't think that makes a difference. 我正在Mac OS X中构建这个应用程序。我不认为这有所作为。 Still, Is HttpClient
the recommended approach for calling a third-party REST API? HttpClient
仍然是调用第三方REST API的推荐方法吗? If not, what should I be using? 如果没有,我应该使用什么? If it is, what am I doing wrong? 如果是的话,我做错了什么?
Thank you! 谢谢!
Did you try Microsoft ASP.NET Web API 2.2 Client Library 您是否尝试过Microsoft ASP.NET Web API 2.2客户端库?
Just add reference to your project.json
file as below: 只需添加对project.json
文件的引用,如下所示:
"dependencies": {
"Microsoft.AspNet.WebApi.Client": "5.2.3"
}
And after package restore, you can call your Web Api like below: 包恢复后,您可以像下面这样调用您的Web Api:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://yourapidomain.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
var product = await response.Content.ReadAsAsync<Product>();
}
}
You can also find a detailed tutorial at http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client 您还可以在http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client找到详细的教程。
I'm looking at the NuGet page for that package . 我正在查看该软件包的NuGet页面 。 The earliest version number is 2.0.20505
. 最早的版本号是2.0.20505
。 Your project specifies anything that's 1.0.0-*
. 您的项目指定了1.0.0-*
任何内容。 Seems like that would exclude a 2.X
version. 似乎会排除2.X
版本。 Try just specifying the latest version 2.2.29
. 请尝试指定最新版本2.2.29
。
Note that I'm not 100% familiar with how vNext resolves packages, so 1.0.0.0-*
could very well pull in a 2.X
package, my answer is just a guess based on the syntax. 请注意,我不是100%熟悉vNext如何解析包,所以1.0.0.0-*
可以很好地1.0.0.0-*
2.X
包,我的答案只是基于语法的猜测。 Let me know if it doesn't work and I'll remove my answer. 如果它不起作用,请告诉我,我会删除我的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.