|
| 1 | +### Validation support in Minimal APIs |
| 2 | + |
| 3 | +<!-- https://github.com/captainsafia/minapi-validation-support --> |
| 4 | + |
| 5 | +Support for validation in Minimal APIs is now available. This feature allows you to request validation of data |
| 6 | +sent to your API endpoints. When validation is enabled, the ASP.NET Core runtime will perform any validations |
| 7 | +defined on query, header, and route parameters, as well as on the request body. |
| 8 | +Validations can be defined using attributes in the `System.ComponentModel.DataAnnotations` namespace. |
| 9 | +Developers can customize the behavior of the validation system by: |
| 10 | + |
| 11 | +- creating custom [ValidationAttribute](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.validationattribute?view=net-9.0) implementations |
| 12 | +- implement the [IValidatableObject](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.ivalidatableobject?view=net-9.0) interface for complex validation logic |
| 13 | + |
| 14 | +When validation fails, the runtime will return a 400 Bad Request response with |
| 15 | +details of the validation errors. |
| 16 | + |
| 17 | +To enable built-in validation support for minimal APIs, call the `AddValidation` extension method to register |
| 18 | +the required services into the service container for your application. |
| 19 | + |
| 20 | +```csharp |
| 21 | +builder.Services.AddValidation(); |
| 22 | +``` |
| 23 | + |
| 24 | +The implementation automatically discovers types that are defined in minimal API handlers or as base types of types defined in minimal API handlers. Validation is then performed on these types by an endpoint filter that is added for each endpoint. |
| 25 | + |
| 26 | +Validation can be disabled for specific endpoints by using the `DisableValidation` extension method. |
| 27 | + |
| 28 | +```csharp |
| 29 | +app.MapPost("/products", |
| 30 | + ([EvenNumber(ErrorMessage = "Product ID must be even")] int productId, [Required] string name) |
| 31 | + => TypedResults.Ok(productId)) |
| 32 | + .DisableValidation(); |
| 33 | +``` |
0 commit comments