Skip to content

ASP.NET Core Minimal API Validator

DodaTech Updated 2026-06-24 1 min read

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);
});
// 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.ValidationProblem with 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

  1. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  2. Using return to exit a function early instead of wrapping a pure value in the monad
  3. 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`.
Does minimal API support model binding errors?

Yes. Invalid JSON or type mismatches return a 400 response automatically.

Can I share validators between minimal API and MVC?

Yes. FluentValidation validators are independent of the hosting model.

For more validation patterns, visit DodaTech.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro