// POST: api/Books public IHttpActionResult Post([FromBody] BookAdd newItem) { // Ensure that the URI is clean (and does not have an id parameter) if (Request.GetRouteData().Values["id"] != null) { return(BadRequest("Invalid request URI")); } // Ensure that a "newItem" is in the entity body if (newItem == null) { return(BadRequest("Must send an entity body with the request")); } // Ensure that we can use the incoming data if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // Attempt to add the new object var addedItem = m.BookAdd(newItem); // Continue? if (addedItem == null) { return(BadRequest("Cannot add the object")); } // HTTP 201 with the new object in the entity body // Notice how to create the URI for the Location header var uri = Url.Link("DefaultApi", new { id = addedItem.Id }); return(Created(uri, addedItem)); }
public BookWithMediaInfo BookAdd(BookAdd newItem) { // Attention 11 - Book add - make sure that the book does not exist before attempting to add it // Lookup using the ISBN // Sanitize the incoming ISBN var isbn = newItem.ISBN13.Trim().ToUpper(); isbn = isbn.Replace(" ", ""); isbn = isbn.Replace("-", ""); var existingItem = ds.Books.SingleOrDefault (b => b.ISBN13 == isbn); if (existingItem != null) { return(null); } // Attempt to add the new object var addedItem = ds.Books.Add(Mapper.Map <Book>(newItem)); // Replace the ISBN with the sanitized version addedItem.ISBN13 = isbn; ds.SaveChanges(); // Return the object return((addedItem == null) ? null : Mapper.Map <BookWithMediaInfo>(addedItem)); }