How to call a RESTful API using ASP.NET 5

Working with ASP.NET 5 on my Mac in Visual Studio Code. I have a RESTful API that I need to call and don't know exactly how to do this. I have seen many examples using WebClient, HttpClient, WebRequest and HttpWebRequest.

I think my sore point is the foundation of dnxcore50. Can someone point me in the right direction with some code samples?

+7
asp.net-core dnx
source share
3 answers

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

The important thing you need to do is install the web API client library package . From the Tools menu, select NuGet Package Manager , then select Package Manager Console . In the Package Manager console window, enter the following command: Install-Package Microsoft.AspNet.WebApi.Client .

For complete source code check this link.

Call service

+7
source share

I assume this is the same as we did before ASP.NET 5, so first you install the NuGet package for ASP.NET client libraries.

With this feature, 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); } 

It just gives you the answer. Generally, you will want to examine the content, especially for GET requests. You can do it:

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

This just gives you a line in the content, so if it is JSON, you probably want to use something like JSON.NET (Newtonsoft.Json) to deserialize it into structured classes.

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

+3
source share

I use the NuGet feed for this https://api.nuget.org/v3/index.json

In my .json project, I currently have these corresponding dependencies and just use the "dnxcore50" structure:

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

Then I use HttpClient. Now (beta7) it does not work on Linux or OSX due to https://github.com/dotnet/corefx/issues/2155 .

+3
source share

All Articles