コード例 #1
0
        public IActionResult CreateBookForAuthor(int authorId, [FromBody] BookForAddDto bookForAdd)  // FromBody signals that it should be deserialized from the request body
        {
            if (bookForAdd == null)
            {
                return(BadRequest());
            }

            if (!Respository.AuthorExists(authorId))
            {
                return(NotFound());
            }

            var bookEntity = Mapper.Map <Book>(bookForAdd);

            Respository.AddBookForAuthor(authorId, bookEntity);

            if (!Respository.Save())
            {
                throw new Exception("Failed to create the book.");  // Throw exception so the middleware handler does all of the error handling.
            }
            var bookToReturn = Mapper.Map <BookDto>(bookEntity);

            return(CreatedAtRoute("GetBookForAuthor", new { authorId, id = bookToReturn.Id }, bookToReturn));   // Puts Location http://localhost:5000/api/Authors/53 in header
        }