Before proceeding to this article, please go through my previous articles:
- ASP.NET WEB API with Entity Framework 6 code first technique- Part I
- ASP.NET WEB API with Entity Framework 6 code first technique- Part 2
- ASP.NET WEB API with Entity Framework 6 code first technique- Part 3
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
- public class Employee
- {
- [Key]
- public int EmployeeId
- {
- get;
- set;
- }
- public string FirstName
- {
- get;
- set;
- }
- public string LastName
- {
- get;
- set;
- }
- public int Age
- {
- get;
- set;
- }
- }
Create a Context class in the project:
- public class CRUDAPIContext : DbContext
- {
- public CRUDAPIContext() : base("name=CRUDAPIContext")
- {
- }
- public System.Data.Entity.DbSet<CRUDAPI.Models.Employee> Employees { get; set; }
- }
- public class EmployeesController : ApiController
- {
- private CRUDAPIContext db = new CRUDAPIContext();
- // GET: api/Employees
- public IQueryable<Employee> GetEmployees()
- {
- return db.Employees;
- }
- // GET: api/Employees/5
- [ResponseType(typeof(Employee))]
- public async Task<IHttpActionResult> GetEmployee(int id)
- {
- Employee employee = await db.Employees.FindAsync(id);
- if (employee == null)
- {
- return NotFound();
- }
- return Ok(employee);
- }
- // PUT: api/Employees/5
- [ResponseType(typeof(void))]
- public async Task<IHttpActionResult> PutEmployee(int id, Employee employee)
- {
- if (!ModelState.IsValid)
- {
- return BadRequest(ModelState);
- }
- if (id != employee.EmployeeId)
- {
- return BadRequest();
- }
- db.Entry(employee).State = EntityState.Modified;
- try
- {
- await db.SaveChangesAsync();
- }
- catch (DbUpdateConcurrencyException)
- {
- if (!EmployeeExists(id))
- {
- return NotFound();
- }
- else
- {
- throw;
- }
- }
- return StatusCode(HttpStatusCode.OK);
- }
- // POST: api/Employees
- [ResponseType(typeof(Employee))]
- public async Task<IHttpActionResult> PostEmployee(Employee employee)
- {
- if (!ModelState.IsValid)
- {
- return BadRequest(ModelState);
- }
- db.Employees.Add(employee);
- await db.SaveChangesAsync();
- return CreatedAtRoute("DefaultApi", new { id = employee.EmployeeId }, employee);
- }
- // DELETE: api/Employees/5
- [ResponseType(typeof(Employee))]
- public async Task<IHttpActionResult> DeleteEmployee(int id)
- {
- Employee employee = await db.Employees.FindAsync(id);
- if (employee == null)
- {
- return NotFound();
- }
- db.Employees.Remove(employee);
- await db.SaveChangesAsync();
- return Ok(employee);
- }
- }
- }




Santhakumar MunuswamyPosted Jan 17, 2016, 2:29 PM
Thanks for nice share
Arul RPosted Jan 17, 2016, 10:43 AM
Nice
Sandeep NeelaPosted Jan 15, 2016, 6:31 AM
Nice Article
Mohammed IbrahimPosted Jan 14, 2016, 9:15 AM
nice
Debasis SahaPosted Jan 14, 2016, 8:16 AM
Good One..