コード例 #1
0
        public IActionResult CreateBook(int authorid,
                                        /* Request body will contain the data for the new book */
                                        [FromBody] BookForCreationDto book)
        {
            // If the data sent is corrupted or empty then it will return a Bad Request.
            if (book == null)
            {
                return(BadRequest());
            }

            // This will generate an error if the Genre and Title are the same.
            if (book.Genre == book.Title)
            {
                ModelState.AddModelError("Genre", "The provided genre should be different from the title.");
            }

            // This will generate an error if the Description and Title are the same.
            if (book.Description == book.Title)
            {
                ModelState.AddModelError("Description", "The provided description should be different from the title.");
            }

            // This will generate an error if the Description and Genre are the same.
            if (book.Description == book.Genre)
            {
                ModelState.AddModelError("Description", "The provided description should be different from the genre.");
            }

            // ModelState is a dictionary that contains state of the model and model binding validations.
            // Will return false if an invalid value is sent.
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var finalBook = Mapper.Map <Entities.Book>(book);

            _bookLibraryRepository.AddBookForAuthor(authorid, finalBook);

            if (!_bookLibraryRepository.Save())
            {
                return(StatusCode(500, "A problem happend while handeling your request."));
            }

            var createdBookToReturn = Mapper.Map <Models.BookDto>(finalBook);

            return(CreatedAtRoute("GetSingleBook", new
                                  { authorId = authorid, id = createdBookToReturn.Id }, createdBookToReturn));
        }