This MSDN link explains why it is a good practice to use DTOs classes for web API. This is understandable, what confuses me is in the same page, the post method uses the model class instead of the simple DTO one as following:
[ResponseType(typeof(BookDTO))]
public async Task<IHttpActionResult> PostBook(Book book)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Books.Add(book);
await db.SaveChangesAsync();
// New code:
// Load author name
db.Entry(book).Reference(x => x.Author).Load();
var dto = new BookDTO()
{
Id = book.Id,
Title = book.Title,
AuthorName = book.Author.Name
};
return CreatedAtRoute("DefaultApi", new { id = book.Id }, dto);
}
I guess my question is: Should Post/Put action takes model or DTO parameter?
Update: From answers, it looks like using dto is recommended even in case of post/put action, this will lead to another question though, how to map from dto to Model class in case of post action? Let's say we use AutoMapper, I found many links such as this and this warn against using it in reverse mapping (i.e. dto => Model class).