DTO - Data Transfer Object
DTO
What we saw till now, (described here), was little bit trivial, cause what we did was maintaining a list of strings. In practice we don't maintain a list of strings or ints or dates. Typically we maintain a list of business objects, like Customer. Order etc.
So let's add a DTO Class. (we will copy it in front of ToDoItemController)
public class TodoItem
{
[MinLength(5)]
[MaxLength(50)]
[Required]
public string Description { get; set; }
[MaxLength(50)]
public string AssignedTo { get; set; }
}
We have also added data annotation to the properties in this DTO. We can define some business rules, for example, what fiedls are mandatory, nimimum and maximum length, etc. The great thing about it, is that we don't have to check that. ASP.NET Core does this automatically. If someone sends a TodoItme without a description ASP.NET Core will recongnize the required attribute and it will return an error.
The changes we will need to do:
-
Change the collection from a list of strings to a list of TodoItem
private static readonly List<TodoItem> items =new List<TodoItem> {new TodoItem { Description = "Clean my room", AssignedTo = "John Dow" },new TodoItem { Description = "Feed the cat", AssignedTo = "Me" }}; -
Change the AddItem method to get in its parameter a TodoItem instead of a string
[HttpPost]public IActionResult AddItem([FromBody] TodoItem newItem){items.Add(newItem);return CreatedAtRoute("GetSpecificItem", new { index = items.IndexOf(newItem) }, newItem);}We get here a complete TodoItem. ASP.NET transform it to TodoItem DTO. All the sanity check, like:
- Is it JSON?
- Does it have a description?
- Does the description have the required length?
are all done Automatically. This is called Model Binding and Model Validation
Model binding
- It is the process of reading data from the request (route values, query string, headers, body/form) and constructing your action parameters / model object.
- Example: JSON in the body is deserialized into TodoItem newItem, or ?sortOrder=desc becomes the sortOrder string parameter.
- 👉 You can read more about model bindings here
Model validation
- Happens after binding, ASP.NET Core checks whether the bound model is valid using validation rules (typically DataAnnotations like [Required], [MinLength], custom validators, etc.).
- In [ApiController] controllers: If validation fails, ASP.NET Core automatically returns 400 with details (without you manually checking ModelState).
Relationship (the usual order)
- Request → model binding → model validation → your action runs (only if valid)
Bibliography:
HTL Perg: Mobile Computing and C# Course - Part 2 (ASP.NET Core Fundamentals) 1:10:57
