ASP.NET Web API Using MVC, Entity Framework And HttpClient For Retrieve Data - Part Four

Introduction
 
.NET 4.5 includes HttpClient class to overcome the limitations of WebClient.  HttpClient class sends and receives data from Web API which is hosted on the local IIS web server. HttpClient is present in other .NET applications also, such as Windows form applications, Windows service applications, etc. There are so many methods of HttpClient to send different HTTP requests as mentioned below.
 
Method Name Method Description
GetAsyncSends a GET request to the specified Uri as an asynchronous operation.
GetByteArrayAsyncSends a GET request to the specified Uri and returns the response body as a byte array in an asynchronous operation.
GetStreamAsyncSends a GET request to the specified Uri and returns the response body as a stream in an asynchronous operation.
GetStringAsyncSends a GET request to the specified Uri and returns the response body as a string in an asynchronous operation.
PostAsyncSends a POST request to the specified Uri as an asynchronous operation.
PostAsJsonAsyncSends a POST request as an asynchronous operation to the specified Uri with the given value serialized as JSON.
PostAsXmlAsyncSends a POST request as an asynchronous operation to the specified Uri with the given value serialized as XML.
PutAsyncSends a PUT request to the specified Uri as an asynchronous operation.
PutAsJsonAsyncSends a PUT request as an asynchronous operation to the specified Uri with the given value serialized as JSON.
PutAsXmlAsyncSends a PUT request as an asynchronous operation to the specified Uri with the given value serialized as XML.
DeleteAsyncSends a DELETE request to the specified Uri as an asynchronous operation.
 
Description
 
In this session, I will show you how to implement Asp.Net Web API Url in controller class file instead of using jQuery. It is possible  to retrieve data from SQL server by using Httpclient class.
 
Go through my previous sessions as mentioned below:
Source Code
Steps to be followed:
 
Step 1
 
Based on my part three session, I will work on this current session to retrieve data using HttpClient. Visit my previous session before going through part four.
 
Here, I have added "Part2" Action into "Home" Controller of SatyaConsumingApi project.
 
Code Ref
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Http;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. using Entities;  
  8.   
  9. namespace SatyaConsumingApi.Controllers  
  10. {  
  11.     public class HomeController : Controller  
  12.     {  
  13.         public ActionResult Part1()  
  14.         {  
  15.             return View();  
  16.         }  
  17.   
  18.         public ActionResult Part2()  
  19.         {  
  20.             List<Employee> list = new List<Employee>();  
  21.             HttpClient client = new HttpClient();  
  22.             var result = client.GetAsync("http://localhost:47250/api/satya").Result;  
  23.             if (result.IsSuccessStatusCode)  
  24.             {  
  25.                 list = result.Content.ReadAsAsync<List<Employee>>().Result; 
  26.             }  
  27.             return View(list);  
  28.         }  
  29.   
  30.     }  
  31. }  
Code Description
 
HttpClient class provides a base class for sending/receiving the HTTP requests/responses from a URL.
  1. HttpClient client = new HttpClient(); 
To access HttpClient class you need to mention namespace as mentioned below...
  1. using System.Net.Http; 
Here, I added a strongly typed list of objects that can be accessed by Index. The employee is an entity model class. To access the Employee class property, use the below-mentioned namespace as described in part three.
  1. using Entities; 
Note 
Remember to add the below-mentioned namespace in SatyaController of SatyaWebApi project because when you are going to use any datacontext as in our project "CrystalGranite2016Entities" or Entity Data Model class file as "Employee" in any project then you should use the namespace with the same name as Class Library name as mentioned below.
  1. using Entities; 
Here, Entities is nothing but the Class Library name, otherwise, you will get an error: "Are you missing a using directive or assembly reference?".
  1. var result = client.GetAsync("http://localhost:47250/api/satya").Result; 
GetAsync is a method of HttpClient class to send a get request to specified Uri as an asynchronous operation. Here I added SatyaWebApi project Url to Retrieve Data.
 
Then after getting the result value from this HttpResponseMessege  check the condition to get a value that indicates if the HTTP response was successful or not. HttpResponseMessage is a way of returning a message/data from your action. HttpResponseMessage works with HTTP protocol to return the data with status/error. We can use HTTPResponseMessage to return the data as well as some user friendly messages.
  1. var result = client.GetAsync("http://localhost:47250/api/satya").Result;  
  2.             if (result.IsSuccessStatusCode)  
  3.             {  
  4.                 
  5.             } 
If the result will be successful then the below code will be executed.
  1. if (result.IsSuccessStatusCode)  
  2.             {  
  3.                 list = result.Content.ReadAsAsync<List<Employee>>().Result;  
  4.             } 
This line of code gets or sets the content of HTTP response message. It returns a Task that will yield an object of the specified type from the content instance.  
 
Note 
To access this ReadAsAsync method you should install one package using NuGet package manager console otherwise you will get an error message "System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method".
  1. PM> install-package Microsoft.AspNet.WebApi.Client 
OR

Just right click on your project, go to Manage NuGet Packages search for Microsoft.AspNet.WebApi.Client install it and you will have access to the extension method. 
 
It is an extension method  in System.Net.Http.Formatting. According to the System.Net.Http.Formatting NuGet package page, the System.Net.Http.Formatting package is now legacy and can instead be found in the Microsoft.AspNet.WebApi.Client package available on NuGet. 
 
Then create a view result object by using the model that renders a view to the response.
  1. return View(list);  
Step 2
 
Add view for the Part2() controller action method of HomeController in SatyaConsumingApi project.
 
Right Click on Action Method (here right click on form action) > Add View... > Check "Create strongly typed view" > Select Model class >> Add. Here Model Class is "Employee (Entities)".
 
 
Code Ref
  1. @model IEnumerable<Entities.Employee>  
  2.   
  3. @{  
  4.     ViewBag.Title = "Satyaprakash - Fetch data from WebAPI using HTTPClient";  
  5. }  
  6.   
  7. <style>  
  8.     table {  
  9.         font-family: arial, sans-serif;  
  10.         border-collapse: collapse;  
  11.         width: 100%;  
  12.     }  
  13.   
  14.     td, th {  
  15.         border: 1px solid #dddddd;  
  16.         text-align: left;  
  17.         padding: 8px;  
  18.     }  
  19.   
  20.     tr:nth-child(even) {  
  21.         background-color: #dddddd;  
  22.     }  
  23. </style>  
  24.   
  25.     <div style="padding:10px ; align-content:center">  
  26.         <fieldset>  
  27.             <legend style="font-family:Arial Black;color:blue">Get Data From Web API Using HTTPClient</legend>  
  28.         </fieldset>  
  29.     </div>  
  30.   
  31.   
  32.     <div id="updatePanel" style="width:90%; padding:10px; margin:0 auto;">  
  33.         <table class="table table-responsive table-striped table-bordered">  
  34.             <thead>  
  35.                 <tr>  
  36.                     <th style="background-color: Yellow;color: blue">Full Name</th>  
  37.                     <th style="background-color: Yellow;color: blue">Email</th>  
  38.                     <th style="background-color: Yellow;color: blue">City</th>  
  39.                     <th style="background-color: Yellow;color: blue">Country</th>  
  40.                 </tr>  
  41.             </thead>  
  42.             <tbody>  
  43.                 @foreach (var i in Model)  
  44.                {  
  45.                     <tr>  
  46.                         <td>@i.FirstName @i.LastName</td>  
  47.                         <td>@i.EmailID</td>  
  48.                         <td>@i.City</td>  
  49.                         <td>@i.Country</td>  
  50.                     </tr>  
  51.                 }  
  52.             </tbody>  
  53.         </table>  
  54.     </div>  
Code Description
 
It uses IEnumerable of Employee as a model object to bind the model with a .cshtml page.
  1. @model IEnumerable<Entities.Employee> 
To loop through Model items in ASP.NET MVC view, use foreach loop in the Controller, which returns Collection of items and in a table under the corresponding column header the column data will be shown.
  1. @foreach (var i in Model)  
  2.                {  
  3.                     <tr>  
  4.                         <td>@i.FirstName @i.LastName</td>  
  5.                         <td>@i.EmailID</td>  
  6.                         <td>@i.City</td>  
  7.                         <td>@i.Country</td>  
  8.                     </tr>  
  9.                 }  
OUTPUT
 
The URL is :  http://localhost:12477/Home/Part2
 
 
SUMMARY
  • Introduction to HttpClient ASP.NET Web API.
  • Steps for retrieving data from the database using HttpClient.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now