public HttpResponseMessage Delete(int id) { try { using (WebAPIDemoEmployeeDBEntities entities = new WebAPIDemoEmployeeDBEntities()) { var entity = entities.Employees.FirstOrDefault(e => e.ID == id); if (entity == null) { //If an item is not found, status code '404 Not Found' is returned. return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee with Id = " + id.ToString() + " not found to delete")); } else { entities.Employees.Remove(entity); entities.SaveChanges(); //When the deletion is successful, status code '200 OK' is returned. return(Request.CreateResponse(HttpStatusCode.OK)); } } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex)); } }
public HttpResponseMessage Put(int id, [FromBody] Employee employee) { try { using (WebAPIDemoEmployeeDBEntities entities = new WebAPIDemoEmployeeDBEntities()) { var entity = entities.Employees.FirstOrDefault(e => e.ID == id); if (entity == null) { //When we try to update an employee whose id does not exist,status code '404 Not Found' is returned return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee with Id " + id.ToString() + " not found to update")); } else { entity.FirstName = employee.FirstName; entity.LastName = employee.LastName; entity.Gender = employee.Gender; entity.Salary = employee.Salary; entities.SaveChanges(); //When the update is successful, status code '200 OK' is returned return(Request.CreateResponse(HttpStatusCode.OK, entity)); } } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex)); } }
public HttpResponseMessage Post([FromBody] Employee employee) { try { using (WebAPIDemoEmployeeDBEntities entities = new WebAPIDemoEmployeeDBEntities()) { entities.Employees.Add(employee); entities.SaveChanges(); //When a new item is created, status code is '201 Item is Created'. //With 201 status code the location i.e URI of the newly created item is also included. var message = Request.CreateResponse(HttpStatusCode.Created, employee); message.Headers.Location = new Uri(Request.RequestUri + employee.ID.ToString()); return(message); } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex)); } }