You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Support for validation in Minimal APIs is now available. This feature allows you to request validation of data sent to your API endpoints. Enabling validation allows the ASP.NET Core runtime to perform any validations defined on the:
76
+
77
+
* Query
78
+
* Header
79
+
* Request body
80
+
81
+
Validations are defined using attributes in the [`DataAnnotations`](xref:System.ComponentModel.DataAnnotations) namespace.
82
+
83
+
When a parameter to a Minimal API endpoint is a class or record type, validation attributes are automatically applied. For example:
84
+
85
+
```csharp
86
+
publicrecordProduct(
87
+
[Required] stringName,
88
+
[Range(1, 1000)] intQuantity);
89
+
```
90
+
Developers customize the behavior of the validation system by:
* Implementing the [`IValidatableObject`](xref:System.ComponentModel.DataAnnotations.IValidatableObject) interface for complex validation logic.
94
+
95
+
If validation fails, the runtime returns a 400 Bad Request response with details of the validation errors.
96
+
97
+
### Enable built-in validation support for minimal APIs
98
+
99
+
Enable the built-in validation support for minimal APIs by calling the `AddValidation` extension method to register the required services in the service container for your application:
100
+
101
+
```csharp
102
+
builder.Services.AddValidation();
103
+
```
104
+
105
+
The implementation automatically discovers types that are defined in minimal API handlers or as base types of types defined in minimal API handlers. An endpoint filter performs validation on these types and is added for each endpoint.
106
+
107
+
Validation can be disabled for specific endpoints by using the `DisableValidation` extension method, as in the following example:
108
+
109
+
```csharp
110
+
app.MapPost("/products",
111
+
([EvenNumber(ErrorMessage="Product ID must be even")] intproductId, [Required] stringname)
112
+
=>TypedResults.Ok(productId))
113
+
.DisableValidation();
114
+
```
115
+
73
116
## Responses
74
117
75
118
Route handlers support the following types of return values:
0 commit comments