Consuming ASP.NET Web API REST Service In ASP.NET MVC Using HttpClient

In this article, we will learn how to consume Web API REST Service in ASP.NET MVC using HttpClient.

Background
 
In many forum posts, developers and students have asked one common question, that is, how to use Web API REST Service in ASP.NET MVC application and how to make a call between them to exchange the information. So, considering this demand, I have decided to write this article to demonstrate how to consume ASP.NET Web API REST Service in ASP.NET MVC application with the help of HttpClient.
 
Prerequisites
 
If you don't know what is Web API REST service and how to create, publish, host ASP.NET Web API REST Service, then please refer to my video as well as articles, using the following links. Also, follow the same sequence if you want to learn web API REST service from creating to hosting to consuming in client application.

In this article, we will use the same hosted Web API REST service to consume in our created ASP.NET MVC web application. Now, let's start consuming Web API REST service in ASP.NET MVC application step by step.

Step 1 - Create MVC Application.
  1. "Start", followed by "All Programs" and select "Microsoft Visual Studio 2015".

  2. Click "File", followed by "New" and click "Project". Select "ASP.NET Web Application Template", provide the Project a name as you wish and click OK. 

  3. After clicking, the following Window will appear. Choose empty project template and check on MVC option.

     
The preceding step creates the simple empty ASP.NET MVC application without Model, View, and Controller, The Solution Explorer of created web application will look like the following.



Step 2 - Install HttpClient library from NuGet

We are going to use HttpClient to consume the Web API REST Service, so we need to install this library from NuGet Package Manager .
 
What is HttpClient ?
 
HttpClient is base class which is responsible to send HTTP request and receive HTTP response resources i.e from REST services.
 
To install HttpClient, right click on Solution Explorer of created application and search for HttpClient, as shown in the following image.

 
Now, click on "Install" button after choosing the appropriate version. It will get installed after taking few seconds, depending on your internet speed.
 
Step 3 - Install WebAPI.Client library from NuGet
 
This package is used for formatting and content negotiation which provides support for System.Net.Http. To install, right click on Solution Explorer of created application and search for WebAPI.Client, as shown in following image.
 
 
 
Now, click on "Install" button after choosing the appropriate version. It will get installed after taking few seconds depending on your internet speed. We have installed necessary NuGet packages to consume Web API REST services in web application. I hope you have followed the same steps.
 
Step 4 - Create Model Class 
 
Now, let us create the Model class named Employee.cs  or as you wish, by right clicking on Models folder with same number of entities which are exposing by our hosted Web API REST service to exchange the data. The code snippet of created Employee.cs class will look like this.
 
Employee.cs
  1. public class Employee  
  2. {  
  3.     public int Id { getset; }  
  4.     public string Name { getset; }  
  5.              
  6.     public string City { getset; }  
  7.   
  8. }   
Step 5 - Add Controller Class
 
Now, let us add ASP.NET MVC controller, as shown in the screenshot given below.

 
After clicking Add button, it will show in the Window. Specify the Controller name as Home with suffix Controller. Now, let's modify the default code of Home controller .
 
Our hosted Web API REST Service includes these two methods, as given below.
  • GetAllEmployees (GET )
  • GetEmployeeById (POST ) which takes id as input parameter
We are going to call GetAllEmployees method which returns the all employee details ,The hosted web api REST service base URL is http://192.168.95.1:5555/ and to call GetAllEmployees from hosted web API REST service, The URL should be Base url+api+apicontroller name +web api method name as following,

http://192.168.95.1:5555/api/Employee/GetAllEmployees

In the preceding url
  • http://localhost:56290 Is the base address of web API service, It can be different as per your server.
  • api It is the used to differentiate between Web API controller and MVC controller request .
  • Employee This is the Web API controller name.
  • GetAllEmployees This is the Web API method which returns the all employee list.
After modifying the code of Homecontroller class, the code will look like the following.
 
Homecontroller.cs
  1. using ConsumingWebAapiRESTinMVC.Models;  
  2. using Newtonsoft.Json;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Net.Http;  
  6. using System.Net.Http.Headers;  
  7. using System.Threading.Tasks;  
  8. using System.Web.Mvc;  
  9.   
  10. namespace ConsumingWebAapiRESTinMVC.Controllers  
  11. {  
  12.     public class HomeController : Controller  
  13.     {  
  14.         //Hosted web API REST Service base url  
  15.         string Baseurl = "http://192.168.95.1:5555/";      
  16.         public async Task<ActionResult> Index()  
  17.         {  
  18.             List<Employee> EmpInfo = new List<Employee>();  
  19.               
  20.             using (var client = new HttpClient())  
  21.             {  
  22.                 //Passing service base url  
  23.                 client.BaseAddress = new Uri(Baseurl);  
  24.   
  25.                 client.DefaultRequestHeaders.Clear();  
  26.                 //Define request data format  
  27.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  28.                   
  29.                 //Sending request to find web api REST service resource GetAllEmployees using HttpClient  
  30.                 HttpResponseMessage Res = await client.GetAsync("api/Employee/GetAllEmployees");  
  31.   
  32.                 //Checking the response is successful or not which is sent using HttpClient  
  33.                 if (Res.IsSuccessStatusCode)  
  34.                 {  
  35.                     //Storing the response details recieved from web api   
  36.                     var EmpResponse = Res.Content.ReadAsStringAsync().Result;  
  37.   
  38.                     //Deserializing the response recieved from web api and storing into the Employee list  
  39.                     EmpInfo = JsonConvert.DeserializeObject<List<Employee>>(EmpResponse);  
  40.   
  41.                 }  
  42.                 //returning the employee list to view  
  43.                 return View(EmpInfo);  
  44.             }  
  45.         }  
  46.     }  

I hope, you have gone through the same steps and understood about the how to use and call Web API REST service resource using HttpClient .
 
Step 6 - Create strongly typed View
 
Now, right click on Views folder of the created application and create strongly typed View named by Index by choosing Employee class to display the employee list from hosted web API REST Service, as shown in the following image.

 
Now, click on "Add" button. It will create View named index after modifying the default code. The code snippet of the Index View looks like the following.

Index.cshtml 
  1. @model IEnumerable<ConsumingWebAapiRESTinMVC.Models.Employee>  
  2.   
  3. @{  
  4.     ViewBag.Title = "www.compilemode.com";  
  5. }  
  6.   
  7. <div class="form-horizontal">  
  8.   
  9.     <hr />  
  10.     <div class="form-group">  
  11.   
  12.   
  13.         <table class="table table-responsive" style="width:400px">  
  14.             <tr>  
  15.                 <th>  
  16.                     @Html.DisplayNameFor(model => model.Name)  
  17.                 </th>  
  18.                 <th>  
  19.                     @Html.DisplayNameFor(model => model.City)  
  20.                 </th>  
  21.                   
  22.             </tr>  
  23.   
  24.             @foreach (var item in Model) {  
  25.                 <tr>  
  26.                     <td>  
  27.                         @Html.DisplayFor(modelItem => item.Name)  
  28.                     </td>  
  29.                     <td>  
  30.                         @Html.DisplayFor(modelItem => item.City)  
  31.                     </td>  
  32.                       
  33.                 </tr>  
  34. }  
  35.   
  36.         </table>  
  37.     </div>  
  38. </div> 
The preceding View will display all employees list . Now, we have done all the coding.

Step 7 - Run the Application
 
After running the Application, the employee list from hosted web API REST service will look like this. 


I hope, from the above examples, you have learned how to consume Web API REST Service in ASP.NET MVC using HttpClient.

Note
  • Download the Zip file of the Published code to learn and start quickly.
  • This article is just guideline on how to consume Web API REST Service in ASP.NET MVC application using HttpClient .
  • In this article, the optimization is not covered in depth; do it as per your skills.

Summary

I hope, this article is useful for all readers. If you have any suggestions, please mention them in the comments section.