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 JavaScript Object Notation (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 it 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 example.

When 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—and you know users 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.

7.1 Extracting values from a request with model binding

7.2 Binding simple types to a request

7.3 Binding complex types to the JSON body

7.4 Arrays: Simple types or complex types?

7.5 Making parameters optional with nullables

7.6 Binding services and special types

7.6.1 Injecting well-known types

7.6.2 Injecting services

7.6.3 Binding file uploads with IFormFile and IFormFileCollection

7.7 Custom binding with BindAsync

7.8 Choosing a binding source

7.9 Simplifying handlers with AsParameters

7.10 Handling user input with model validation

sitemap