Some User
Some User

Reputation: 5817

How to use HttpClient in ASP.NET Core app

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!

Upvotes: 3

Views: 4138

Answers (2)

CemilF
CemilF

Reputation: 125

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

Upvotes: 4

mason
mason

Reputation: 32693

I'm looking at the NuGet page for that package. The earliest version number is 2.0.20505. Your project specifies anything that's 1.0.0-*. Seems like that would exclude a 2.X version. Try just specifying the latest version 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. Let me know if it doesn't work and I'll remove my answer.

Upvotes: 2

Related Questions