📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you validate requests in ASP.NET Core? Cover DataAnnotations, the automatic 400 from [ApiController], FluentValidation, and the built-in Minimal API validation added in .NET 10. Where do business rules belong compared with input validation?

Request validation in ASP.NET Core .NET 10: DataAnnotations and IValidatableObject, ModelState and the [ApiController] automatic ValidationProblemDetails 400, FluentValidation (manual or via filters), AddValidation() for Minimal APIs, and the split between input validation and domain/business rules.

Intermediate Theory Intermediate aspnet-core dataannotations fluentvalidation minimal-apis problem-details validation

🎯 Key points

  • DataAnnotations ([Required], [Range], [StringLength], [EmailAddress]) suffice for per-field rules on request DTOs and also appear in OpenAPI; IValidatableObject covers cross-field rules on one DTO
  • Controllers: model binding fills ModelState; [ApiController] returns a 400 ValidationProblemDetails automatically before the action runs
  • .NET 10 Minimal APIs: builder.Services.AddValidation() source-generates validation for parameters (nested types and collections included) and returns a 400 ProblemDetails
  • FluentValidation for conditional, collection, configuration-driven or async rules; call ValidateAsync explicitly or from an endpoint/action filter (automatic MVC integration is deprecated)
  • Input validation (shape, ranges, formats) at the edge; business rules (stock, uniqueness, state transitions) in the application or domain layer so they are reusable from APIs, messages and jobs
  • Uniqueness and similar rules need the database constraint as the final guard, because check-then-insert races
  • Return the same ValidationProblemDetails shape for input and business errors (errors dictionary keyed by field)
  • Never trust client-side validation; validate on the server every time

⏱ 30-second answer

I validate input at the edge and business rules in the application or domain layer. For input, DataAnnotations ([Required], [Range], [StringLength]) and IValidatableObject on request DTOs are the baseline. In controllers, binding fills ModelState and [ApiController] returns a 400 ValidationProblemDetails before the action runs. In Minimal APIs on .NET 10, builder.Services.AddValidation() uses a source generator to validate parameters and return the same 400 ProblemDetails; before .NET 10 you needed a filter. FluentValidation is my choice for complex, conditional or async rules; I call it explicitly or from a filter, because its automatic MVC integration is deprecated. Business rules like stock levels or uniqueness are checked where the data lives and returned in the same error shape. The trade-off: attributes are simple and visible in OpenAPI; code-based validators are more expressive.

🗣 Full answer (senior)

How I would answer this in an interview

"I split validation into two layers. Input validation answers 'is this request well formed?': required fields, lengths, ranges, formats. That belongs at the edge, on the request DTO. Business validation answers 'is this allowed right now?': is the product in stock, is the email already taken, can this order still be cancelled. That belongs in the application or domain layer, next to the data.

For input I start with DataAnnotations on records, plus IValidatableObject for cross-field rules like 'end date after start date'. In controllers, model binding runs validation into ModelState, and [ApiController] short-circuits with a 400 ValidationProblemDetails listing errors per field, so the action never runs with invalid input. Minimal APIs didn't have that until .NET 10: now builder.Services.AddValidation() source-generates validators for the types used as parameters and returns the same ProblemDetails 400, including for nested objects and collections. For rules that are conditional, depend on configuration or need a database lookup, I use FluentValidation, but I call IValidator<T>.ValidateAsync explicitly or wrap it in an endpoint filter; the old auto-validation package is deprecated because async rules ran synchronously inside the MVC pipeline.

The mistake I see is pushing business rules into attributes or validators that hit the database, so every validation becomes a query and the rule lives in two places. The senior goal is one error contract: whether a field is too long or the product is discontinued, the client gets a ValidationProblemDetails with the field name and a message."


Options

Mechanism Where it runs Best for
DataAnnotations Model binding (MVC) or AddValidation() (Minimal APIs) Simple per-field rules, visible in OpenAPI
IValidatableObject Same Cross-field rules on one DTO
FluentValidation Your code or a filter Conditional, collection and async rules
Domain/application checks Handler or domain model Business invariants

Input vs business validation

Input validation Business validation
Question Is the request well formed? Is it allowed now?
Example Quantity between 1 and 100 Enough stock for 40 units
Needs data store? No Usually
Status code 400 400, 409 or 422 (be consistent)
Where DTO attributes / validators Application service, domain

Production example

Moving FluentValidation calls that queried the database for uniqueness out of validators and into the command handler removed one extra SQL round trip per request (about 3–5 ms each) and fixed a race where two concurrent requests both passed the 'email is unique' validator; the unique index plus a 409 on DbUpdateException became the single source of truth.

🔍 What the interviewer is checking

Checks whether the candidate validates in the right places and gives clients a consistent error contract.

Green flags

  • Separates input validation from business rules.
  • Knows the [ApiController] automatic 400 and .NET 10 AddValidation().
  • Uses FluentValidation explicitly and knows the auto-validation package is deprecated.
  • Mentions races and database constraints for uniqueness.

Red flags

  • Thinks Minimal APIs validate automatically in all versions.
  • Puts database queries in validators without considering races.
  • Returns 200 with an error flag for invalid input.

📚 Learn in depth

1. How MVC validation works

Model binding ─► ObjectModelValidator walks the bound object graph
              ─► DataAnnotations attributes + IValidatableObject.Validate
              ─► errors added to ModelState (key = property path, e.g. "Lines[0].Quantity")
              ─► [ApiController]: ModelStateInvalidFilter returns 400 ValidationProblemDetails

Validation is recursive over properties and collections, up to MvcOptions.MaxValidationDepth (32). Non-nullable reference types are treated as [Required] when nullable context is enabled (SuppressImplicitRequiredAttributeForNonNullableReferenceTypes controls it).

2. .NET 10 Minimal API validation

builder.Services.AddValidation() registers a validation endpoint filter. A source generator (part of the Microsoft.AspNetCore.App framework analysers) finds types used as handler parameters that have validation attributes, and emits validation code, so it works with trimming and Native AOT. Errors are returned through IProblemDetailsService as a 400. You can opt out per endpoint with .DisableValidation(). It validates query, header and body parameters, nested types and collections, and supports IValidatableObject and custom ValidationAttributes.

3. FluentValidation

Validators are classes deriving from AbstractValidator<T> with rules like RuleFor(x => x.Email).NotEmpty().EmailAddress(). Recommended integration today:

  • Inject IValidator<T> and call ValidateAsync in the handler, then return TypedResults.ValidationProblem(result.ToDictionary()); or
  • A generic endpoint filter ValidationFilter<T> that resolves IValidator<T> and short-circuits.

The FluentValidation.AspNetCore auto-validation hooked into MVC's synchronous validation pipeline, so async rules couldn't run properly; it is deprecated.

4. Business rules

Business rules need current state and often concurrency control. A validator that checks 'email not taken' with a query has a race window; the database unique constraint is the real guard. Domain methods (order.Cancel()) enforce invariants and return or throw domain errors that the API maps to ProblemDetails.

5. Error contract

ValidationProblemDetails (RFC 9457 shape) has type, title, status, errors (dictionary of field → messages) and, from ASP.NET Core, a traceId extension. Use it for both input and business errors so clients have one parser.

Try it yourself

  1. Add [Range(1, 100)] to a Minimal API DTO without AddValidation(), post 500, then add it and compare.
  2. Implement IValidatableObject for a date range and check the error key.
  3. Write a ValidationFilter<T> for FluentValidation and apply it to a route group.
  4. Fire two concurrent 'register' requests with the same email and see which layer catches the duplicate.
  5. Inspect the OpenAPI schema for a DTO with DataAnnotations and confirm maxLength/minimum appear.

💻 Code

DataAnnotations with .NET 10 Minimal API validation, a FluentValidation rule called explicitly, and a business rule returning the same error shape.

// Program.cs
using System.ComponentModel.DataAnnotations;
using FluentValidation;
using Microsoft.AspNetCore.Http.HttpResults;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
builder.Services.AddValidation();                                   // .NET 10: validates DataAnnotations on parameters
builder.Services.AddScoped<IValidator<CreateBooking>, CreateBookingValidator>();
builder.Services.AddScoped<IBookingService, BookingService>();
var app = builder.Build();

app.MapPost("/bookings", async Task<Results<Created<BookingDto>, ValidationProblem, Conflict<string>>> (
    CreateBooking cmd, IValidator<CreateBooking> validator, IBookingService bookings, CancellationToken ct) =>
{
    // DataAnnotations already ran (400 before we get here). FluentValidation for conditional rules:
    var result = await validator.ValidateAsync(cmd, ct);
    if (!result.IsValid) return TypedResults.ValidationProblem(result.ToDictionary());

    // Business rule: needs current state, lives in the service, same error contract
    return await bookings.CreateAsync(cmd, ct) switch
    {
        BookingResult.Created c => TypedResults.Created($"/bookings/{c.Booking.Id}", c.Booking),
        BookingResult.RoomUnavailable => TypedResults.ValidationProblem(new Dictionary<string, string[]>
            { [nameof(cmd.RoomId)] = ["The room is not available for those dates."] }),
        _ => TypedResults.Conflict("Booking could not be created.")
    };
});

app.Run();

// Input validation on the DTO: visible in OpenAPI, runs before the handler
public sealed record CreateBooking(
    [Range(1, int.MaxValue)] int RoomId,
    [Required, EmailAddress, StringLength(254)] string Email,
    DateOnly CheckIn,
    DateOnly CheckOut,
    [Range(1, 6)] int Guests) : IValidatableObject
{
    public IEnumerable<ValidationResult> Validate(ValidationContext context)
    {
        if (CheckOut <= CheckIn)
            yield return new("Check-out must be after check-in.", [nameof(CheckOut)]);
    }
}

// Conditional rule that would be awkward as attributes
public sealed class CreateBookingValidator : AbstractValidator<CreateBooking>
{
    public CreateBookingValidator() =>
        RuleFor(x => x.CheckOut).Must((cmd, checkOut) => checkOut.DayNumber - cmd.CheckIn.DayNumber <= 28)
            .WithMessage("Bookings longer than 28 nights must be made by phone.");
}

public sealed record BookingDto(int Id, int RoomId);
public abstract record BookingResult
{
    public sealed record Created(BookingDto Booking) : BookingResult;
    public sealed record RoomUnavailable : BookingResult;
}
public interface IBookingService { Task<BookingResult> CreateAsync(CreateBooking cmd, CancellationToken ct); }

⚠ Common mistakes

  • Mistake: Assuming Minimal APIs validate DataAnnotations without setup. Why it is wrong: Even in .NET 10 nothing runs until you call AddValidation(); earlier versions never validated. Instead: Register it and test an invalid request.
  • Mistake: Checking ModelState.IsValid manually in every [ApiController] action. Why it is wrong: The filter already returned 400; the check is dead code. Instead: Remove it and customise InvalidModelStateResponseFactory once if needed.
  • Mistake: Database lookups inside validators for uniqueness. Why it is wrong: Every request pays an extra round trip, and there is a race: requests A and B both run SELECT ... WHERE Email = @e, both see no row, both pass validation and both insert, so you get duplicates or an unhandled DbUpdateException from the index. Instead: Enforce with a unique index and map the violation to a 409 or a field error.
  • Mistake: Using the deprecated FluentValidation auto-validation for MVC. Why it is wrong: Async rules run synchronously or not at all, and it's no longer supported. Instead: Call validators explicitly with ValidateAsync or from a filter.
  • Mistake: Different error shapes for input and business errors. Why it is wrong: Clients need two parsers and UIs can't highlight fields consistently. Instead: Use ValidationProblemDetails for both.
  • Mistake: Relying on client-side validation. Why it is wrong: Anyone can call the API directly. Instead: Always validate on the server.
  • Mistake: Putting business rules in DataAnnotations on entities or in HTTP-only validators. Why it is wrong: It couples persistence models to HTTP, and the same rule is skipped when the command arrives from a queue or a job. Instead: DTO attributes for input; domain methods or application services for invariants.

🏛 Senior insight: trade-offs

The senior answer is about placement and contract, not libraries. Input validation is cheap and belongs at the edge so invalid requests never reach your handlers; business invariants belong where the state is, with the database as the final guard against races. The framework now covers the common case in both models ([ApiController] and .NET 10 AddValidation()), so FluentValidation is a choice for expressiveness, not a necessity.

Option When it fits Cost When not to
DataAnnotations + AddValidation() / [ApiController] Most DTOs Limited expressiveness Complex conditional rules
FluentValidation (explicit) Conditional, collection, config-driven rules Extra dependency, rules not in OpenAPI Simple required/range checks
Domain invariants Business rules, state transitions More modelling Pure format checks
Database constraints Uniqueness, referential integrity Exception mapping As the only validation (poor messages)

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the automatic 400 in controllers. Why: Checks deeper knowledge of [ApiController] behaviours and customising the 400 response.
    How to answer

    In MVC, a controller is a class whose public methods are actions; each action becomes an endpoint and returns an action result (IActionResult, or ActionResult<T> for a typed body plus status codes). API controllers derive from ControllerBase; Controller adds view support. [ApiController] makes API behaviour explicit: attribute routing is required, an invalid ModelState returns an automatic 400 ValidationProblemDetails, binding sources are inferred (complex types from the body), and error status codes become ProblemDetails. For server-rendered UI there are two styles: MVC with Razor Views (a controller picks a .cshtml view) and Razor Pages (a .cshtml page with its own PageModel and OnGet/OnPost handlers). Razor Pages fits page-per-task, form-heavy apps; MVC fits when one controller serves many views or shares logic with APIs.

  2. When: Candidate mentions .NET 10 Minimal API validation. Why: Checks how validation differences influence the Minimal APIs vs controllers decision.
    How to answer

    Both sit on the same foundation: endpoint routing, middleware, DI, authentication and OpenAPI. The difference is the programming model. Minimal APIs map handlers directly with MapGet/MapPost, organise with route groups, return TypedResults, use endpoint filters, support Native AOT, and in .NET 10 get built-in DataAnnotations validation with AddValidation(). Controllers group actions in classes and bring the full MVC feature set: [ApiController] behaviours (automatic 400s, binding inference), the five MVC filter types, custom model binders, input/output formatters with content negotiation and JSON Patch. For a new API service I default to Minimal APIs organised by feature; I choose controllers when the team relies on MVC filters, formatters or existing conventions. The trade-off is less ceremony and AOT versus a richer, more conventional framework.

↩ Usually asked after

More in Request Handling

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me