Richard.Davenport
Richard.Davenport

Reputation: 1501

How to call a RESTful API with ASP.NET 5

Working with ASP.NET 5 on my Mac in Visual Studio Code. I have a RESTful API I need to call and not sure exactly how to do it. I've seen many examples using WebClient, HttpClient, WebRequest and HttpWebRequest.

I think my pain point is the dnxcore50 framework. Can someone please point me in the right direction with some code samples?

Upvotes: 11

Views: 17229

Answers (3)

Triet Doan
Triet Doan

Reputation: 12085

Here is an example about how to call a service. Please check the References and using carefully.

One important thing you have to do is install the Web API Client Libraries package: From the Tools menu, select NuGet Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command: Install-Package Microsoft.AspNet.WebApi.Client.

For the full source code, check this link.

Call service

Upvotes: 9

opiethehokie
opiethehokie

Reputation: 1912

To do this I'm using the NuGet feed https://api.nuget.org/v3/index.json

In my project.json I currently have these relevant dependencies and just use the "dnxcore50" framework:

"Microsoft.AspNet.WebApi.Client": "5.2.3",
"System.Net.Http": "4.0.0",
"System.Runtime.Serialization.Xml": "4.0.10"

Then I'm using HttpClient. Right now (beta7) it doesn't work on Linux or OSX because of https://github.com/dotnet/corefx/issues/2155.

Upvotes: 3

Gigi
Gigi

Reputation: 29421

I'm assuming it's the same way we used to do it prior to ASP .NET 5, so first you install the ASP .NET Web API Client Libraries NuGet package.

With that available, you reference System.Net.Http:

using System.Net.Http;

Then you use it as follows:

using (var httpClient = new HttpClient())
{
    var response1 = await httpClient.GetAsync(url1);
    var response2 = await httpClient.PostAsync(url2);
    var response3 = await httpClient.SendAsync(url3);
}

That just gives you the response. Typically you'll want to look into the content, especially for GET requests. You can do this by:

var content = await response1.Content.ReadAsStringAsync();

That merely gives you the string in the content, so if it's JSON, you probably want to use something like JSON.NET (Newtonsoft.Json) to deserialize it into structured classes.

This is from memory so you might need a little tweak here and there.

Upvotes: 4

Related Questions