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

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. HttpResponseMessage response = client.GetAsync("http://localhost:57135/api/Employees/1").Result;
  12. if (response.IsSuccessStatusCode)
  13. {
  14. Employee emp = await response.Content.ReadAsAsync<Employee> ();
  15. Console.WriteLine("{0}\t{1}\t{2}\t{3}", emp.EmployeeId, emp.FirstName, emp.LastName, emp.Age);
  16. Console.ReadKey();
  17. }
  18. }
  19. }
  20. }

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. var addEmp = new Employee() { FirstName = "John", LastName = "Miller", Age = 25 };
  13. HttpResponseMessage response = client.PostAsJsonAsync("http://localhost:57135/api/Employees", addEmp).Result;
  14. Console.WriteLine("{0}\t{1}", "StatusCode:", response.StatusCode);
  15. Console.ReadKey();
  16. }
  17. }
  18. }
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. var updateEmp = new Employee() {EmployeeId=3, FirstName = "John", LastName = "Miller", Age = 27 };
  13. HttpResponseMessage response = client.PutAsJsonAsync("http://localhost:57135/api/Employees/3", updateEmp).Result;
  14. Console.WriteLine("{0}\t{1}", "StatusCode:", response.StatusCode);
  15. Console.ReadKey();
  16. }
  17. }
  18. }
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. HttpResponseMessage response = client.DeleteAsync("http://localhost:57135/api/Employees/3").Result;
  13. Console.WriteLine("{0}\t{1}", "StatusCode:", response.StatusCode);
  14. Console.ReadKey();
  15. }
  16. }
  17. }
Result
Reflection in SQL Table


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