Display Data From Hosted Web API REST Service in ASP.NET MVC Using HttpClient

Many reader asking me to write on how to get data from remotely hosted web API REST service , So I have decided to write this article to explain step by step how to display data from hosted web API REST Service in ASP.NET MVC using HttpClient. To demonstrate this lets create simple ASP.NET MVC application
If are new and wants 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 ASP.NET 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.



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.

    public class Employee  
    {  
        public int Id { get; set; }  
        public string Name { get; set; }  
                 
        public string City { get; set; }  
      
    }   

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 
The url of the hosted web API REST Service is 

  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
using ConsumingWebAapiRESTinMVC.Models;  
using Newtonsoft.Json;  
using System;  
using System.Collections.Generic;  
using System.Net.Http;  
using System.Net.Http.Headers;  
using System.Threading.Tasks;  
using System.Web.Mvc;  
  
namespace ConsumingWebAapiRESTinMVC.Controllers  
{  
    public class HomeController : Controller  
    {  
        //Hosted web API REST Service base url  
        string Baseurl = "http://192.168.95.1:5555/";      
        public async Task<ActionResult> Index()  
        {  
            List<Employee> EmpInfo = new List<Employee>();  
              
            using (var client = new HttpClient())  
            {  
                //Passing service base url  
                client.BaseAddress = new Uri(Baseurl);  
  
                client.DefaultRequestHeaders.Clear();  
                //Define request data format  
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
                  
                //Sending request to find web api REST service resource GetAllEmployees using HttpClient  
                HttpResponseMessage Res = await client.GetAsync("api/Employee/GetAllEmployees");  
  
                //Checking the response is successful or not which is sent using HttpClient  
                if (Res.IsSuccessStatusCode)  
                {  
                    //Storing the response details recieved from web api   
                    var EmpResponse = Res.Content.ReadAsStringAsync().Result;  
  
                    //Deserializing the response recieved from web api and storing into the Employee list  
                    EmpInfo = JsonConvert.DeserializeObject<List<Employee>>(EmpResponse);  
  
                }  
                //returning the employee list to view  
                return View(EmpInfo);  
            }  
        }  
    }  
}  

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 
@model IEnumerable<ConsumingWebAapiRESTinMVC.Models.Employee>  
  
@{  
    ViewBag.Title = "www.compilemode.com";  
}  
  
<div class="form-horizontal">  
  
    <hr />  
    <div class="form-group">  
  
  
        <table class="table table-responsive" style="width:400px">  
            <tr>  
                <th>  
                    @Html.DisplayNameFor(model => model.Name)  
                </th>  
                <th>  
                    @Html.DisplayNameFor(model => model.City)  
                </th>  
                  
            </tr>  
  
            @foreach (var item in Model) {  
                <tr>  
                    <td>  
                        @Html.DisplayFor(modelItem => item.Name)  
                    </td>  
                    <td>  
                        @Html.DisplayFor(modelItem => item.City)  
                    </td>  
                      
                </tr>  
}  
  
        </table>  
    </div>  
</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

  • 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 the readers. If you have any suggestions, please contact me.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode