3

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!

ilkerkaran
  • 4,214
  • 3
  • 27
  • 42
Some User
  • 5,257
  • 13
  • 51
  • 93
  • possible duplicate of [HttpClient in ASP.NET 5.0 not found?](http://stackoverflow.com/questions/27946798/httpclient-in-asp-net-5-0-not-found) – Patrick Hofman May 18 '15 at 13:26
  • Can't answer your missing binary question, but HttpClient is the preferred (newer version) of the API to use (over WebClient) – Jamie Pollard May 18 '15 at 13:37
  • @PatrickHofman That approach seems outdated. Yet, I tried following the approach found in the [GitHub repo](https://github.com/aspnet/HttpClient/blob/dev/samples/TestClient/project.json) and I still get the same error. – Some User May 18 '15 at 14:10
  • Okay, I retracted my close vote. – Patrick Hofman May 18 '15 at 14:11

2 Answers2

4

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

CemilF
  • 126
  • 1
  • 6
2

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.

mason
  • 31,774
  • 10
  • 77
  • 121