-
-
Save tuannguyenssu/41d4d0942d33ee0c33dce541436db934 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using MongoDBTest.Models; | |
using MongoDBTest.Services; | |
using Microsoft.AspNetCore.Mvc; | |
using System.Collections.Generic; | |
namespace MongoDBTest.Controllers | |
{ | |
[Route("api/[controller]")] | |
[ApiController] | |
public class BooksController : ControllerBase | |
{ | |
private readonly BookService _bookService; | |
public BooksController(BookService bookService) | |
{ | |
_bookService = bookService; | |
} | |
[HttpGet] | |
public ActionResult<List<Book>> Get() => | |
_bookService.Get(); | |
[HttpGet("{id:length(24)}", Name = "GetBook")] | |
public ActionResult<Book> Get(string id) | |
{ | |
var book = _bookService.Get(id); | |
if (book == null) | |
{ | |
return NotFound(); | |
} | |
return book; | |
} | |
[HttpPost] | |
public ActionResult<Book> Create(Book book) | |
{ | |
_bookService.Create(book); | |
return CreatedAtRoute("GetBook", new { id = book.Id.ToString() }, book); | |
} | |
[HttpPut("{id:length(24)}")] | |
public IActionResult Update(string id, Book bookIn) | |
{ | |
var book = _bookService.Get(id); | |
if (book == null) | |
{ | |
return NotFound(); | |
} | |
_bookService.Update(id, bookIn); | |
return NoContent(); | |
} | |
[HttpDelete("{id:length(24)}")] | |
public IActionResult Delete(string id) | |
{ | |
var book = _bookService.Get(id); | |
if (book == null) | |
{ | |
return NotFound(); | |
} | |
_bookService.Remove(book.Id); | |
return NoContent(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment