How to use HttpClient in ASP.NET Core app
I am trying to create an app with ASP.NET Core (aka vNext). I need to call third party REST API. Traditionally, I would use HttpClient. However, I cannot 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 get the error: "Unable to find Microsoft.Net.Http.Client> = 1.0. 0- *". Another post referenced by the commenter is out of date.
I am building this application on Mac OS X. I don't think it matters. That said, is the HttpClient
recommended approach for calling third party REST APIs? If not, what should I use? If so, what am I doing wrong?
Thank!
source to share
Have you tried Microsoft ASP.NET Web API 2.2 Client Library
Just add a link to your project.json
file like below:
"dependencies": {
"Microsoft.AspNet.WebApi.Client": "5.2.3"
}
And after restoring the package, 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 guide at http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
source to share
I am looking at the NuGet page for this package . Earliest version number 2.0.20505
. Your project states something that 1.0.0-*
. It looks like it would rule out the version 2.X
. Try to include only the latest version 2.2.29
.
Please note that I am not 100% familiar with how vNext resolves packages, so it 1.0.0.0-*
can insert a package very well 2.X
, my answer is just a guess based on the syntax. Let me know if that doesn't work and I'll delete my answer.
source to share