diff --git a/aspnetcore/fundamentals/minimal-apis.md b/aspnetcore/fundamentals/minimal-apis.md index 632f7852c6ae..97dfe63d41f0 100644 --- a/aspnetcore/fundamentals/minimal-apis.md +++ b/aspnetcore/fundamentals/minimal-apis.md @@ -5,7 +5,7 @@ description: Provides an overview of minimal APIs in ASP.NET Core ms.author: wpickett content_well_notification: AI-contribution monikerRange: '>= aspnetcore-6.0' -ms.date: 02/07/2025 +ms.date: 05/19/2025 uid: fundamentals/minimal-apis ai-usage: ai-assisted --- @@ -70,6 +70,49 @@ The arguments passed to these methods are called "route h [!INCLUDE [](~/fundamentals/minimal-apis/includes/parameter-binding10.md)] +## Validation support in Minimal APIs + +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: + +* Query +* Header +* Request body + +Validations are defined using attributes in the [`DataAnnotations`](xref:System.ComponentModel.DataAnnotations) namespace. + +When a parameter to a Minimal API endpoint is a class or record type, validation attributes are automatically applied. For example: + +```csharp +public record Product( + [Required] string Name, + [Range(1, 1000)] int Quantity); +``` +Developers customize the behavior of the validation system by: + +* Creating custom [`[Validation]`](xref:System.ComponentModel.DataAnnotations.ValidationAttribute) attribute implementations. +* Implementing the [`IValidatableObject`](xref:System.ComponentModel.DataAnnotations.IValidatableObject) interface for complex validation logic. + +If validation fails, the runtime returns a 400 Bad Request response with details of the validation errors. + +### Enable built-in validation support for minimal APIs + +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: + +```csharp +builder.Services.AddValidation(); +``` + +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. + +Validation can be disabled for specific endpoints by using the `DisableValidation` extension method, as in the following example: + +```csharp +app.MapPost("/products", + ([EvenNumber(ErrorMessage = "Product ID must be even")] int productId, [Required] string name) + => TypedResults.Ok(productId)) + .DisableValidation(); +``` + ## Responses Route handlers support the following types of return values: