Consuming Rest API methods in .NET Core MVC application

Up until we need to rely on third party libraries for consuming a Web API in .NET Core applications. Even though Microsoft has got the Microsoft.AspNet.WebApi.Client library that can be used for consuming API methods, the support for .NET Core was not there until now. This library had a dependency on Microsoft.Net.Http library which was not supported in .NET Core. So with the release of the 5.2.3 version of Microsoft.AspNet.WebApi.Client they have fixed this issue and now it's available for you to use in .NET Core web applications too.

Step 1 : Add reference in project.json

You need to add following entries under dependencies section in the project.json file as given below.

The Microsoft.AspNet.WebApi.Client is dependent on System.Net.Http and System.Runtime.Serialization.Xml libraries and that's why we need to add the above ones in the json file

Step 2 : Use HttpClient to consume API

We will use an object of the HttpClient class in the System.Net.Http namespace which was rebuilt for supporting .NET Core in latest version to invoke a connection to the service and for consuming the method. Then we will the base address and request headers using the BaseAddress and DefaultRequestHeaders methods respectively. To consume the web method, we will use the GetAysnc method which returns a resposne stream object containing the response from the Web API and by using the ReadAsAsync to read the result from the stream

For other operations such as Post, Put and Delete we can use PostAsAsync, PutAsJsonAsync, DeleteAsync

For more please refer here: http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client


No Comments

Add a Comment

Recent Posts