MinimalApis.Extensions adds DataAnnotations-based parameter validation to ASP.NET Core minimal API endpoints through the WithParameterValidation() extension method. After model binding, its validation filter either invokes the handler or returns a 400 Bad Request Problem Details response. section 7.10.3
Validate a request model
Map a POST endpoint accepting UserModel, decorate its Name and Email properties with attributes such as [Required], [StringLength], and [EmailAddress], then call .WithParameterValidation(). Invalid request data produces validation errors without executing the handler. section 7.10.3
Use the extension with these practical patterns:
- Install the MinimalApis.Extensions NuGet package, including prerelease versions when necessary. section 7.10.3
- Validate complex bound types directly through their DataAnnotations attributes. section 7.10.3
- Validate simple values by wrapping them in a containing type marked with [AsParameters], then placing attributes such as [Range] on its properties. section 7.10.3 section 7.11
Listing 7.12 Adding validation to minimal APIs using MinimalApis.Extensions
using System.ComponentModel.DataAnnotations;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
app.MapPost("/users", (UserModel user) => user.ToString())
.WithParameterValidation(); #1
app.Run();
public record UserModel #2
{
[Required]
[StringLength(100)]
[Display(Name = "Your name")]
public string Name { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
}
#1 Adds the validation filter to the endpoint
#2 The UserModel defines its validation requirements using DataAnnotations attributes.
Shows the complete endpoint, model, validation attributes, and WithParameterValidation() call. section 7.10.3
