ASP.NET Core Minimal API Validator
In this tutorial, you'll learn about ASP.NET Core Minimal API Validator. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Your minimal API endpoints accept request bodies but you have no validation. Invalid data causes confusing database errors.
Wrong
app.MapPost("/api/users", (User user) =>
{
// No validation — saves garbage data
return Results.Ok(user);
});
Right
// Using FluentValidation
public class UserValidator : AbstractValidator<User>
{
public UserValidator()
{
RuleFor(u => u.Name).NotEmpty().MaximumLength(100);
RuleFor(u => u.Email).EmailAddress();
}
}
app.MapPost("/api/users", async (User user, IValidator<User> validator) =>
{
var validationResult = await validator.ValidateAsync(user);
if (!validationResult.IsValid)
return Results.ValidationProblem(validationResult.ToDictionary());
return Results.Ok(user);
});
Or inline with endpoint filter:
app.MapPost("/api/users", (User user) => Results.Ok(user))
.AddEndpointFilter<ValidationFilter<User>>();
Prevention
- Use a validator (FluentValidation, DataAnnotations, or custom) for all input models.
- Return
Results.ValidationProblemwith structured validation errors. - Use endpoint filters to apply validation automatically.
- Register validators in DI:
<a href="/design-patterns/builder/">Builder</a>.Services.AddValidatorsFromAssemblyContaining<UserValidator>(). - Validate in production to prevent data corruption.
Common Mistakes with core minimal validator
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world ASPNET code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Can I use DataAnnotations with minimal APIs?
Yes. Use `[Required]`, `[EmailAddress]`, etc. on your model and call `Validator.TryValidateObject`.For more validation patterns, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro