7 Model binding and validation in minimal APIs
This chapter covers
- Using request values to create binding models
- Customizing the model-binding process
- Validating user input using
DataAnnotations
attributes
In chapter 6 I showed you how to define a route with parameters—perhaps for the unique ID for a product API. But say a client sends a request to the product API—what then? How do you access the values provided in the request, and read the JSON in the request body?
For most of this chapter, in sections 7.1-7.9, we’ll look at model binding, and how it simplifies reading data from a request in minimal APIs. You’ll see how to take the data posted in the request body or in the URL and bind them to C# objects, which are then passed to your endpoint handler methods as arguments. When your handler executes, it can use these values to do something useful—return a product’s details or change a product’s name, for instance.
Once your code is executing in an endpoint handler method, you might be forgiven for thinking that you can happily use the binding model without any further thought. Hold on though, where did that data come from? From a user—you know they can’t be trusted! Section 7.10 focuses on how to make sure that the user-provided values are valid and make sense for your app.