Creating And Calling A Web API From A .NET Client In ASP.NET Web API 2

ASP.NET Web API is a framework from .Net which helps in building HTTP services that reach all ranges of clients, including browsers and mobile devices, such as Windows, iOS and Android. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. 

Here, in this post, I am going to explain about the following things:
  • Creating WEB API for CRUD operations.
  • Testing each WEB API using Postman clients.
  • Consuming these  API in MVC Project using HttpClient.
  • A complete tutorial of CRUD operations in Webgrid in MVC Project using WEB API.
Before starting this tutorial, I will show the Project Flow diagram from which you will get the basic idea of how I am going to do it.
 

So, here, I will work with two projects, as you see in the diagram. The first is my WebAPI project  where I will create various WEBAPIs according to my requirement. Here, I will create 4 APIs for my Crud operation. After that, I will host my WEB API project on local IIS.

Now, I will start my first project to create the WebAPI.

Create a WEB API project and add a WEBAPI 2 Empty Controller, as follows:



Now, in this, I have my Employee.cs  Model, as follows:
  1. public class Employee  
  2.    {  
  3.        public int EmpId { getset; }  
  4.        public string EmpName { getset; }  
  5.        public string CompanyName { getset; }  
  6.        public string Location { getset; }  
  7.        public int Dept { getset; }  
  8.        public string ContactNo { getset; }  
  9.        public string Address { getset; }  
  10.       
  11.    }  
Now, Add the following ADO.NET Entity Data Model and add the following code to connect it to the database.

  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using System.Data.EntityModel;  
  8. using System.Data.Entity;  
  9. using System.Threading.Tasks;  
  10.   
  11. namespace MYWEBAPI.Controllers  
  12. {  
  13.     [RoutePrefix("api/Employee")]  
  14.     
  15.     public class EmployeeController : ApiController  
  16.     {  
  17.         StudentsEntities SE = new StudentsEntities();  
  18.         [Route("SaveDetails")]  
  19.         [HttpPost]  
  20.         public async Task<IHttpActionResult> SaveDetails(Employee emp)  
  21.         {  
  22.             Dictionary<stringstring> dict = new Dictionary<stringstring>();  
  23.   
  24.             SE.Employees.Add(emp);  
  25.             if(SE.SaveChanges()==1)  
  26.             {  
  27.                 dict.Add("Message""Data Saved Successfully.");  
  28.                 return Ok(dict);  
  29.             }  
  30.             else  
  31.             {  
  32.                 dict.Add("Error""Data Not saved.");  
  33.                 return Ok(dict);  
  34.             }  
  35.   
  36.   
  37.   
  38.         }  
  39.         [HttpPost]  
  40.         [Route("UpdateDetails")]  
  41.   
  42.         public async Task<IHttpActionResult> UpdateDetails(Employee emp)  
  43.         {  
  44.             Dictionary<stringstring> dict = new Dictionary<stringstring>();  
  45.             var details = SE.Employees.Where(x => x.EmpId == emp.EmpId).SingleOrDefault();  
  46.             if(details!=null)  
  47.             {  
  48.                 details.EmpName = emp.EmpName;  
  49.                 details.CompanyName = emp.CompanyName;  
  50.                 details.Dept = emp.Dept;  
  51.                 details.Location = emp.Location;  
  52.                 if(SE.SaveChanges()==1)  
  53.                 {  
  54.                     dict.Add("Message""Data Updated Successfully.");  
  55.                     return Ok(dict);  
  56.   
  57.                 }  
  58.                 else  
  59.                 {  
  60.                     dict.Add("Error""Data Not saved.");  
  61.                     return Ok(dict);  
  62.   
  63.                 }  
  64.   
  65.             }  
  66.             else  
  67.             {  
  68.                 dict.Add("Error""Invalid UserId");  
  69.                 return Ok(dict);  
  70.   
  71.             }  
  72.   
  73.              
  74.   
  75.   
  76.   
  77.         }  
  78.         [Route("getDetails")]  
  79.         [HttpGet]  
  80.         public IHttpActionResult  getDetails()  
  81.         {  
  82.             List<Employee> li = new List<Employee>();  
  83.             var details = SE.Employees.ToList();  
  84.             if (details != null)  
  85.             {  
  86.                 return Ok(details);  
  87.             }  
  88.             else  
  89.             {  
  90.                 return NotFound();   
  91.   
  92.             }  
  93.   
  94.         }  
  95.         [Route("DeleteEmployee")]  
  96.         [HttpPost]  
  97.         public IHttpActionResult DeleteEmployee(Employee eemp)  
  98.         {  
  99.             Dictionary<stringstring> dict = new Dictionary<stringstring>();  
  100.             List<Employee> li = new List<Employee>();  
  101.             var details = SE.Employees.Where(x => x.EmpId == eemp.EmpId).FirstOrDefault();  
  102.             bool result = false;  
  103.             SE.Employees.Remove(details);  
  104.             if(SE.SaveChanges()==1)  
  105.             {  
  106.   
  107.                 dict.Add("Message","Employee Deleted Successfully.");  
  108.                 return Ok(dict);  
  109.             }  
  110.             else  
  111.             {  
  112.                 dict.Add("Message""Employee Not Deleted.");  
  113.                 return Ok(dict);  
  114.   
  115.             }  
  116.   
  117.         }  
  118.          
  119.           
  120.     }  
  121. }  
After that, use the Postman Client to test WEB APIs. First of all, we will check the first API for saving the data. 

 

In the same way, we check all the APIs in the Postman. After completing the checking of all the APIs, we just host all the APIs on IIS.
 
Now, we will start our second MVC project work where we will consume the APIs.
 
So,  add a new MVC Project. Here is my solution Explorer with a model added.



Here is the Employee.cs  class model which contains the same fields as Employee.cs in WEB API Projects, with some additional fields as follows:
  1. public class Employees  
  2.     {  
  3.         public int EmpId { getset; }  
  4.         public string EmpName { getset; }  
  5.         public string CompanyName { getset; }  
  6.         public string Location { getset; }  
  7.         public string Dept { getset; }  
  8.         public string ContactNo { getset; }  
  9.         public string Address { getset; }  
  10.        
  11.     }  
 Now, in the Home Controller, I have the following code to show the data in EmployeeDetails view: 
  1. public class HomeController : Controller  
  2.     {  
  3.         public async Task<ActionResult> EmployeeDetails()  
  4.         {  
  5.             Employees Model = new Employees();  
  6.             using (var client = new HttpClient())  
  7.             {  
  8.                 client.BaseAddress = new Uri("http://localhost:28661/");  
  9.                 client.DefaultRequestHeaders.Accept.Clear();  
  10.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  11.                 ViewBag.country = "";  
  12.                 HttpResponseMessage response = await client.GetAsync("api/Employee/getDetails");  
  13.                 List<string> li;  
  14.                 if (response.IsSuccessStatusCode)  
  15.                 {  
  16.                     Employees obj = new Employees();  
  17.   
  18.                     var details = response.Content.ReadAsAsync<IEnumerable<Employees>>().Result;  
  19.                     return View(details);  
  20.   
  21.   
  22.                 }  
  23.                 else  
  24.                 {  
  25.                     return View();  
  26.   
  27.                 }  
  28.             }  
  29.   
  30.   
  31.         }  
Here, I used HttpClient to call the getDetails API from API Project which is hosted in IIS. After getting the result from API, I am sending the data to the View. In View, I have a webgrid to show the data.

Here is the code to view the data, and EDIT,UPDATE,CANCEL,DELETE the data from web Grid.  
  1. @model IEnumerable<MVCProject.Models.Employees>   
  2. @{  
  3.     ViewBag.Title = "EmployeeDetails";  
  4. }  
  5.   
  6. <h2>EmployeeDetails</h2>  
  7. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  8. <script src="~/Scripts/bootstrap.min.js"></script>  
  9.   
  10. <style type="text/css">  
  11.      
  12.    .webgrid-table {  
  13.         font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;  
  14.         font-size: 1.2em;  
  15.         width:300px;  
  16.         display: table;  
  17.         border-collapse: separate;  
  18.         border: solid 1px;  
  19.         background-color:purple;  
  20.     }  
  21.   
  22.     .webgrid-table td, th {  
  23.         border: 3px solid ;  
  24.         padding: 3px 7px 2px;  
  25.         width:230px;  
  26.     }  
  27.   
  28.     .webgrid-header {  
  29.         background-color:cornsilk;  
  30.         color: #FFFFFF;  
  31.         padding-bottom: 4px;  
  32.         padding-top: 5px;  
  33.         text-align: left;  
  34.         width:20%;  
  35.     }  
  36.   
  37.     .webgrid-footer {  
  38.     }  
  39.   
  40.     .webgrid-row-style {  
  41.         padding: 3px 7px 2px;  
  42.     }  
  43.   
  44.     .webgrid-alternating-row {  
  45.         background-color: #EAF2D3;  
  46.         padding: 3px 7px 2px;  
  47.     }  
  48.   
  49.     </style > <h2 > Index</h2 >  
  50. <script type="text/javascript">  
  51.      
  52.     $(function () {    
  53.         $('.edit-mode').hide();    
  54.         $('.edit-user, .cancel-user').on('click', function ()  
  55.         {    
  56.             var tr = $(this).parents('tr:first');    
  57.             tr.find('.edit-mode, .display-mode').toggle();    
  58.         });  
  59.         $('.Delete-user').on('click', function () {  
  60.             if (confirm("Are you sure?")) {  
  61.                 var tr = $(this).parents('tr:first');  
  62.                 var ID = tr.find("#lbl_Empid").html();  
  63.                 var UserModel =  
  64.                 {  
  65.                     "EmpId": ID  
  66.                 }  
  67.                 $.ajax({  
  68.                     url: '/Home/DeleteUser/',  
  69.                     data: JSON.stringify(UserModel),  
  70.                     type: 'POST',  
  71.                     contentType: 'application/json; charset=utf-8',  
  72.                     success: function (data) {  
  73.                         location.reload();  
  74.                     }  
  75.   
  76.                 });  
  77.             }  
  78.             else  
  79.             {  
  80.                 var tr = $(this).parents('tr:first');  
  81.                 tr.find('.edit-mode, .display-mode').toggle();  
  82.   
  83.             }  
  84.         });  
  85.         $('.save-user').on('click', function () {    
  86.             var tr = $(this).parents('tr:first');    
  87.             var ID = tr.find("#lbl_Empid").html();  
  88.             var Name = tr.find("#txt_employeeName").val();    
  89.             var Location = tr.find("#txt_location").val();    
  90.             var Department = tr.find("#txt_dept").val();  
  91.             var companyName = tr.find("#txt_company").val();  
  92.   
  93.              
  94.             tr.find("#lblemployeename").text(Name);  
  95.             tr.find("#lbl_dept").text(Department);  
  96.             tr.find("#lbl_company").text(companyName);  
  97.             tr.find("#lbl_location").text(Location);  
  98.             tr.find('.edit-mode, .display-mode').toggle();    
  99.             var UserModel =    
  100.             {    
  101.                 "EmpId": ID,  
  102.                 "EmpName": Name,  
  103.                 "Location": Location,  
  104.                 "Dept": Department,  
  105.                 "CompanyName": companyName  
  106.   
  107.             };    
  108.             $.ajax({    
  109.                 url: '/Home/Update/',    
  110.                 data: JSON.stringify(UserModel),    
  111.                 type: 'POST',    
  112.                 contentType: 'application/json; charset=utf-8',    
  113.                 success: function (data) {    
  114.                     window.location.href = window.location.href;  
  115.                 }   
  116.               
  117.             });  
  118.           
  119.         });  
  120.     })  
  121. </script>  
  122.   
  123.   
  124.    
  125.   
  126. <div>@{  
  127.     var grid = new WebGrid(source: Model, canPage: true, rowsPerPage: 10);  
  128.     grid.Pager(WebGridPagerModes.All);  
  129. }  
  130.   
  131. </div>  
  132. <h3>List Of Users</h3>  
  133. <div>  
  134.     @grid.GetHtml(  
  135.                    headerStyle: "webgrid-header",  
  136.                 footerStyle: "webgrid-footer",  
  137.                 alternatingRowStyle: "webgrid-alternating-row",  
  138.                 selectedRowStyle: "webgrid-selected-row",  
  139.                 rowStyle: "webgrid-row-style",  
  140.                 mode: WebGridPagerModes.All,  
  141.              columns: grid.Columns(  
  142.                
  143.               grid.Column("EmpId", format: @<text>  <span  class="display-mode">@item.EmpId </span> <label id="lbl_Empid" class="edit-mode">@item.EmpId</label> </text>, style: "col1Width" ),  
  144.                 
  145.                                 grid.Column(columnName: "EmpName", header: "EmployeeName", format: @<text> <span  class="display-mode">@item.EmpName <label id="lblemployeename"></label> </span>  <input type="text" id="txt_employeeName" value="@item.EmpName" class="edit-mode" /> </text>, style: "col2Width"),  
  146.                  
  147.                                                        grid.Column(columnName: "Dept", header: "Department", format: @<text> <span  class="display-mode">@item.Dept <label id="lbl_dept"></label> </span>  <input type="text" id="txt_dept" value="@item.Dept" class="edit-mode" /> </text>, style: "col2Width"),  
  148.               
  149.                                                            grid.Column(columnName: "CompanyName", header: "CompanyName", format: @<text> <span  class="display-mode">@item.CompanyName <label id="lbl_company"></label> </span>  <input type="text" id="txt_company" value="@item.CompanyName" class="edit-mode" /> </text>, style: "col2Width"),  
  150.                  
  151.                   
  152.                   grid.Column(columnName:"Location",header:"Location", format: @<text> <span  class="display-mode">@item.Location <label id="lbllocation"></label> </span>  <input type="text" id="txt_location" value="@item.Location" class="edit-mode" /> </text>, style: "col2Width"),  
  153.                    
  154.                   grid.Column("Action", format: @<text>   
  155.      
  156.                                  <button class="edit-user display-mode" style="background-color: #1E90FF; border-bottom-style: groove">Edit</button>  
  157.                                        <button class="save-user edit-mode" style="background-color: #FF5733; border-bottom-style: groove">Save</button>  
  158.                                           <button class="cancel-user edit-mode" style="background-color: #FF5733; border-bottom-style: groove">Cancel</button>  
  159.                                    <button class="Delete-user display-mode" style="background-color: #1E90FF; border-bottom-style: groove">Delete</button>  
  160.                             </text>,  style: "col3Width" , canSort:true)))  
  161.   
  162.   
  163.   
  164.   
  165.   
  166.   
  167.   
  168. </div>  
First of all, when we will call the EmployeeDetails method and Home controller, it will give the following View:
  1. http://localhost:30517/Home/EmployeeDetails  


Now, when we click the EDIT button, the View will look like this:


Now, change any field and click Save.

 
After clicking Save, it will call the following Action Method in Home Controller and update the Data.  
  1. public async Task<ActionResult> Update(Employees employee)    
  2.        {    
  3.            using (var client = new HttpClient())    
  4.            {    
  5.                client.BaseAddress = new Uri("http://localhost:28661/");    
  6.                client.DefaultRequestHeaders.Accept.Clear();    
  7.                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));    
  8.     
  9.                //HttpResponseMessage response = await     
  10.                var Result = client.PostAsJsonAsync("api/Employee/UpdateDetails", employee).Result;    
  11.                if (Result.IsSuccessStatusCode == true)    
  12.                {    
  13.                    return View();    
  14.     
  15.                }    
  16.                else    
  17.                {    
  18.                    return View();    
  19.                }    
  20.            }    
  21.        }    

Now, write the following ActionMethod in Home controller to delete the selected user:
  1. public async Task<ActionResult> DeleteUser(Employees employee)  
  2.        {  
  3.            using (var client = new HttpClient())  
  4.            {  
  5.                client.BaseAddress = new Uri("http://localhost:28661/");  
  6.                client.DefaultRequestHeaders.Accept.Clear();  
  7.                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  8.   
  9.                //HttpResponseMessage response = await   
  10.                var Result = client.PostAsJsonAsync("api/Employee/DeleteEmployee", employee).Result;  
  11.                if(Result.IsSuccessStatusCode==true)  
  12.                {  
  13.                    return View();  
  14.   
  15.                }  
  16.                else  
  17.                {  
  18.                    return View();  
  19.                }  
  20.            }  
Now, click the Delete Button on the View.
 

If you click OK, it will call the API and Delete the User.

So, this way, we can do CRUD operation in WebGrid by consuming the API.
 
I hope this article will help to learn these initial steps toward Creating and Consuming WEB API with complete CRUD operation of Webgrid. If I missed anything, please mention in the comments,  so that I can implement that the next time.