ASP.NET controllers should be thin
Oh, this ever-repeated platitude, overgrown with tons of understatement.
Why should they be thin? What's the plus? How to make them thin if they are not so now? How do you keep them thin?
, , .
, 6 , , . , , .
1. (DTO)
, , - , , HTTP.
, - :
public IActionResult CheckOutBook([FromBody]BookRequest bookRequest)
{
var book = new Book();
book.Title = bookRequest.Title;
book.Rating = bookRequest.Rating.ToString();
book.AuthorID = bookRequest.AuthorID;
//...
}
, , . HTTP .
2.
, , . , .
, -. , . ASP.NET MVC, .
!
public IActionResult Register([FromBody]AutomobileRegistrationRequest request)
{
// , VIN ...
if (string.IsNullOrEmpty(request.VIN))
{
return BadRequest();
}
//...
}
3. -
-, , - .
. , ( ), , .
4.
, . , , .
, ASP.NET ( , ).
User
, / -, , , - .
5.
, !
public IActionResult GetBookById(int id)
{
try
{
// , -...
}
catch (DoesNotExistException)
{
// , ...
}
catch (Exception e)
{
// , ...
}
}
, , , , , . , , - .
-, - . , , - .
6. /
, ,
. CRUD , , .
, .
, , , , .
( ). , , .
public IActionResult CheckOutBook(BookRequest request)
{
var book = _bookRepository.GetBookByTitleAndAuthor(request.Title, request.Author);
// ,
//
// ...
return Ok(book);
}
CRUD , , , .
( ) - CQRS .
!
, , ? - ? ? !
, , , 5 .
UPD:
4 , , . ยซ ?ยป ยซ ?ยป.
, , , , . , โ HTTP . , HTTP , HTTP .
ยซ , ?ยป ยซ ?ยป โ , , .