在ASP.NET 5应用程序中使用HttpClient(How to use HttpClient in ASP.NET Core app)

编程入门 行业动态 更新时间:2024-10-11 19:21:26
在ASP.NET 5应用程序中使用HttpClient(How to use HttpClient in ASP.NET Core app)

我正在尝试使用ASP.NET 5(aka vNext)构建一个应用程序。 我需要调用第三方REST-API。 传统上,我会使用HttpClient。 但是,我似乎无法让它工作。 在我的project.json文件中,我有:

"dependencies": { "Microsoft.Net.Http.Client": "1.0.0-*" }

当我运行dnu restore ,我收到一条错误消息:“无法找到Microsoft.Net.Http.Client> = 1.0.0- *”。 评论者提到的另一篇文章是过时的。

我正在Mac OS X中构建这个应用程序。我不认为这会有所作为。 HttpClient仍然是调用第三方REST API的推荐方法吗? 如果没有,我应该使用什么? 如果是的话,我做错了什么?

谢谢!

I am trying to build an app with ASP.NET Core (aka vNext). I need to call a third-party REST-API. Traditionally, I would use HttpClient. However, I can't seem to get it to work. In my project.json file I have:

"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-*". 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. Still, Is HttpClient the recommended approach for calling a third-party REST API? If not, what should I be using? If it is, what am I doing wrong?

Thank you!

最满意答案

您是否尝试过Microsoft ASP.NET Web API 2.2客户端库?

只需添加对您的project.json文件的引用,如下所示:

"dependencies": { "Microsoft.AspNet.WebApi.Client": "5.2.3" }

在包恢复之后,您可以像下面这样调用您的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>(); } }

您还可以在http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client找到详细的教程。

Did you try Microsoft ASP.NET Web API 2.2 Client Library

Just add reference to your project.json file as below:

"dependencies": { "Microsoft.AspNet.WebApi.Client": "5.2.3" }

And after package restore, you can call your Web Api like below:

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

更多推荐

本文发布于:2023-08-04 03:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1405348.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应用程序   NET   ASP   app   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!