ASP.NET WEB API With Entity Framework 6 Code First Technique - Part 4

Before proceeding to this article, please go through my previous articles:

In this article we are going to learn how to call ASP.NET WEB API from .NET Application.

Create One Employee model class in the project

  1. public class Employee  
  2. {  
  3.     [Key]  
  4.     public int EmployeeId   
  5.     {  
  6.         get;  
  7.         set;  
  8.     }  
  9.     public string FirstName  
  10.     {  
  11.         get;  
  12.         set;  
  13.     }  
  14.     public string LastName  
  15.     {  
  16.         get;  
  17.         set;  
  18.     }  
  19.     public int Age  
  20.     {  
  21.         get;  
  22.         set;  
  23.     }  
  24. }  

 

Create a Context class in the project:

  1. public class CRUDAPIContext : DbContext  
  2.    {     
  3.        public CRUDAPIContext() : base("name=CRUDAPIContext")  
  4.        {  
  5.        }  
  6.   
  7.        public System.Data.Entity.DbSet<CRUDAPI.Models.Employee> Employees { getset; }  
  8.    }  
The Employees Controller class
  1. public class EmployeesController : ApiController  
  2.     {  
  3.         private CRUDAPIContext db = new CRUDAPIContext();  
  4.   
  5.         // GET: api/Employees  
  6.         public IQueryable<Employee> GetEmployees()  
  7.         {  
  8.             return db.Employees;  
  9.         }  
  10.   
  11.         // GET: api/Employees/5  
  12.         [ResponseType(typeof(Employee))]  
  13.         public async Task<IHttpActionResult> GetEmployee(int id)  
  14.         {  
  15.             Employee employee = await db.Employees.FindAsync(id);  
  16.             if (employee == null)  
  17.             {  
  18.                 return NotFound();  
  19.             }  
  20.   
  21.             return Ok(employee);  
  22.         }  
  23.   
  24.         // PUT: api/Employees/5  
  25.         [ResponseType(typeof(void))]  
  26.         public async Task<IHttpActionResult> PutEmployee(int id, Employee employee)  
  27.         {  
  28.             if (!ModelState.IsValid)  
  29.             {  
  30.                 return BadRequest(ModelState);  
  31.             }  
  32.   
  33.             if (id != employee.EmployeeId)  
  34.             {  
  35.                 return BadRequest();  
  36.             }  
  37.   
  38.             db.Entry(employee).State = EntityState.Modified;  
  39.   
  40.             try  
  41.             {  
  42.                 await db.SaveChangesAsync();  
  43.             }  
  44.             catch (DbUpdateConcurrencyException)  
  45.             {  
  46.                 if (!EmployeeExists(id))  
  47.                 {  
  48.                     return NotFound();  
  49.                 }  
  50.                 else  
  51.                 {  
  52.                     throw;  
  53.                 }  
  54.             }  
  55.   
  56.             return StatusCode(HttpStatusCode.OK);  
  57.         }  
  58.   
  59.         // POST: api/Employees  
  60.         [ResponseType(typeof(Employee))]  
  61.         public async Task<IHttpActionResult> PostEmployee(Employee employee)  
  62.         {  
  63.             if (!ModelState.IsValid)  
  64.             {  
  65.                 return BadRequest(ModelState);  
  66.             }  
  67.   
  68.             db.Employees.Add(employee);  
  69.             await db.SaveChangesAsync();  
  70.   
  71.             return CreatedAtRoute("DefaultApi"new { id = employee.EmployeeId }, employee);  
  72.         }  
  73.   
  74.         // DELETE: api/Employees/5  
  75.         [ResponseType(typeof(Employee))]  
  76.         public async Task<IHttpActionResult> DeleteEmployee(int id)  
  77.         {  
  78.             Employee employee = await db.Employees.FindAsync(id);  
  79.             if (employee == null)  
  80.             {  
  81.                 return NotFound();  
  82.             }  
  83.   
  84.             db.Employees.Remove(employee);  
  85.             await db.SaveChangesAsync();  
  86.   
  87.             return Ok(employee);  
  88.         }  
  89. }  
  90. }  

SQL Table

  
 

Our API’s are ready, so now we can call these API from the .NET Application. In my case I’m taking a console Application.

Create one console Application:

Installing the WEB API Client libraries:

Use NuGet Package Manager to install the Web API Client Libraries package for Console Application or else use Install –Package Microsoft.AspNet.WebApi.Client command in package manager console. 

 

Create a Model class in Console Application

  1. public class Employee  
  2. {  
  3.     public int EmployeeId   
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string FirstName   
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public string LastName   
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public int Age   
  19.     {  
  20.         get;  
  21.         set;  
  22.     }  
  23. }  

Call GetEmployees API Action from Console Application using HTTP Client

HTTP Client:

It is a class which is from System.Net.Http Namespace and provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.

Example

  1. class Program  
  2.   {  
  3.       static void Main(string[] args)  
  4.       {  
  5.           ApiCall().Wait();  
  6.       }  
  7.       static async Task ApiCall()  
  8.       {  
  9.           using (var client = new HttpClient())  
  10.           {  
  11.                
  12.               HttpResponseMessage response =  client.GetAsync("http://localhost:57135/api/Employees/1").Result;  
  13.               if (response.IsSuccessStatusCode)  
  14.               {  
  15.                    
  16.                   Employee emp = await response.Content.ReadAsAsync<Employee> ();  
  17.                     
  18.                   Console.WriteLine("{0}\t{1}\t{2}\t{3}", emp.EmployeeId, emp.FirstName, emp.LastName, emp.Age);  
  19.                   Console.ReadKey();  
  20.                    
  21.               }  
  22.           }  
  23.       }  
  24.   }  

Result



Call Employees POST API Action
  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             ApiCall();  
  6.         }  
  7.         static void ApiCall()  
  8.         {  
  9.             using (var client = new HttpClient())  
  10.             {  
  11.                 //HTTP POST  
  12.   
  13.                 var addEmp = new Employee() { FirstName = "John", LastName = "Miller", Age = 25 };  
  14.                 HttpResponseMessage response =  client.PostAsJsonAsync("http://localhost:57135/api/Employees", addEmp).Result;  
  15.                 Console.WriteLine("{0}\t{1}""StatusCode:", response.StatusCode);  
  16.                 Console.ReadKey();  
  17.   
  18.                   
  19.             }  
  20.         }  
  21.     }  
Result

 
 
Reflection in SQL Table
 


Call Employees PUT API Action
  1. class Program  
  2.    {  
  3.        static void Main(string[] args)  
  4.        {  
  5.            ApiCall();  
  6.        }  
  7.        static void ApiCall()  
  8.        {  
  9.            using (var client = new HttpClient())  
  10.            {  
  11.                //HTTP PUT  
  12.   
  13.                var updateEmp = new Employee() {EmployeeId=3, FirstName = "John", LastName = "Miller", Age = 27 };  
  14.                
  15.                HttpResponseMessage response =  client.PutAsJsonAsync("http://localhost:57135/api/Employees/3", updateEmp).Result;  
  16.                Console.WriteLine("{0}\t{1}""StatusCode:", response.StatusCode);  
  17.                Console.ReadKey();                   
  18.                  
  19.            }  
  20.         }  
  21.         }  
Result
 
  
 
 Reflection in SQL Table
 


Call Employees Delete API Action
  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             ApiCall();  
  6.         }  
  7.         static void ApiCall()  
  8.         {  
  9.             using (var client = new HttpClient())  
  10.             {  
  11.                 //HTTP DELETE               
  12.                 
  13.                 HttpResponseMessage response =  client.DeleteAsync("http://localhost:57135/api/Employees/3").Result;  
  14.                 Console.WriteLine("{0}\t{1}""StatusCode:", response.StatusCode);  
  15.                 Console.ReadKey();    
  16.                   
  17.             }  
  18.         }  
  19.     }  
Result
 
  
 
Reflection in SQL Table
 
  

I hope you enjoyed this article. Your valuable feedback, question, or comments about this article are always welcomed.