// POST api/camera public HttpResponseMessage Post(Camera newCamera) { if(ModelState.IsValid) { try { InMemoryCameraRepo.SingletonInstance.AddCamera(newCamera); var response = Request.CreateResponse(HttpStatusCode.Created, newCamera); var location = string.Format("{0}{1}{2}", Url.Request.RequestUri.OriginalString, "/", newCamera.Id); response.Headers.Location = new Uri(location); //Set location, so that the client knows where to find the newly created resource return response; } catch (Exception ex) { ThrowHttpResponseException(HttpStatusCode.BadRequest, ex); //400 } } var modelValidationErrorResponse = Request.CreateResponse(HttpStatusCode.BadRequest); modelValidationErrorResponse.Content = new StringContent(ModelState.GetModelErrors()); return modelValidationErrorResponse; }
public void AddCamera(Camera camera) { if (!CameraExists(camera.Id ?? 0)) { _cameras.Add(camera); } else { throw new Exception(string.Format("Unable to create camera. Camera with Id={0} already exists.", camera.Id)); } }
// PUT api/camera/5 public HttpResponseMessage Put(Camera camera) { if (ModelState.IsValid) { try { InMemoryCameraRepo.SingletonInstance.UpdateCamera(camera); var response = Request.CreateResponse(HttpStatusCode.OK, camera); //Return 200 return response; } catch (Exception ex) { ThrowHttpResponseException(HttpStatusCode.NotFound, ex); } } var modelValidationErrorResponse = Request.CreateResponse(HttpStatusCode.BadRequest); modelValidationErrorResponse.Content = new StringContent(ModelState.GetModelErrors()); return modelValidationErrorResponse; }
public void UpdateCamera(Camera camera) { var cameraToUpdate = _cameras.SingleOrDefault(x => x.Id == camera.Id); if(cameraToUpdate != null) { cameraToUpdate.Brand = camera.Brand; cameraToUpdate.Model = camera.Model; cameraToUpdate.Price = camera.Price; } else { throw new Exception(string.Format("Unable to update camera. Camera with id={0} not found.", camera.Id)); } }