skip to content

In ASP.NET Core 10 Minimal APIs, how would you run IValidator<T> for a group of loan endpoints with a reusable filter, and how does that compare with built-in AddValidation?

level: seniorimportance: should knowfreq 38%

answer

  1. IEndpointFilter wrapping the handler
  2. find the argument in context.Arguments
  3. typed filter built from RequestServices
  4. short-circuit with ValidationProblem
  5. AddValidation covers DataAnnotations only

basics

~10 s

Write a generic IEndpointFilter that takes IValidator<T>, finds the T argument in context.Arguments, awaits ValidateAsync and returns TypedResults.ValidationProblem on failure, otherwise calls next. ASP.NET Core 10's AddValidation validates DataAnnotations and IValidatableObject, not FluentValidation rules.

solid answer

~40 s

A `ValidationFilter<T> : IEndpointFilter` receives `IValidator<T>` through its constructor; `AddEndpointFilter<ValidationFilter<LoanApplication>>()` creates the filter per request from `HttpContext.RequestServices`, so a scoped validator is safe. In `InvokeAsync`, it takes `context.Arguments.OfType<T>().FirstOrDefault()`, awaits `ValidateAsync(argument, context.HttpContext.RequestAborted)`, and on failure returns `TypedResults.ValidationProblem(result.ToDictionary())` without calling `next`. Applied to a route group, every endpoint that takes a `LoanApplication` is validated, and handlers stay free of validation code. ASP.NET Core 10's built-in `builder.Services.AddValidation()` is different: it validates DataAnnotations attributes and `IValidatableObject` on query, header and body values through a source generator and returns 400 automatically. It does not run FluentValidation rules, so teams on FluentValidation keep the filter, or move rules to attributes to use the built-in feature.

go deeper

for a junior

Know that an endpoint filter can run validation before a Minimal API handler and stop the request with a ValidationProblem.

for a middle

Write the generic filter: find the argument, await ValidateAsync with RequestAborted, short-circuit on failure, pass through otherwise.

for a senior

Reason about filter activation and scopes, apply it per group safely, and compare it honestly with .NET 10's AddValidation.

for a principal

Choose one request-validation strategy per service portfolio, balancing FluentValidation's expressiveness against fewer dependencies with built-in validation.

## Why a filter Calling `ValidateAsync` in every handler works, but a lending API with a dozen endpoints repeats the same five lines. An **endpoint filter** runs around a Minimal API handler, can read its bound arguments, and can return a result instead of calling the handler. (The endpoint filter API itself, ordering and factories, is a Minimal API topic; this answer is about putting validation in one.) ## A generic validation filter ```csharp public sealed class ValidationFilter<T>(IValidator<T> validator) : IEndpointFilter { public async ValueTask<object?> InvokeAsync( EndpointFilterInvocationContext context, EndpointFilterDelegate next) { var argument = context.Arguments.OfType<T>().FirstOrDefault(); if (argument is null) return await next(context); // endpoint has no T to validate var result = await validator.ValidateAsync(argument, context.HttpContext.RequestAborted); if (!result.IsValid) return TypedResults.ValidationProblem(result.ToDictionary()); return await next(context); } } ``` ```csharp var loans = app.MapGroup("/loan-applications"); loans.MapPost("/", SubmitLoan) .AddEndpointFilter<ValidationFilter<LoanApplication>>(); loans.MapPut("/{id:guid}", UpdateLoan) .AddEndpointFilter<ValidationFilter<LoanApplication>>(); ``` How it behaves: 1. **Activation per request.** `AddEndpointFilter<TFilterType>()` builds the filter with `ActivatorUtilities` from `context.HttpContext.RequestServices` on each invocation, so the scoped `IValidator<LoanApplication>` comes from the request's scope. 2. **Finding the argument.** `context.Arguments` holds the handler's bound arguments in order; `OfType<T>()` avoids hard-coding an index. When the endpoint has no `T`, the filter passes through. 3. **Short-circuit.** Returning `TypedResults.ValidationProblem(...)` skips the handler and writes a 400 with the `errors` dictionary. 4. **Cancellation.** `HttpContext.RequestAborted` stops the async rules (a credit-bureau lookup) when the client disconnects. A filter **instance** is different: `AddEndpointFilter(new ValidationFilter<LoanApplication>(validator))` shares one object across all requests, so it must not hold a scoped validator. ## What the built-in validation in ASP.NET Core 10 does ASP.NET Core 10 added validation for Minimal APIs: ```csharp builder.Services.AddValidation(); ``` | | FluentValidation filter | Built-in `AddValidation` | |---|---|---| | Rule source | `AbstractValidator<T>` classes | DataAnnotations attributes and `IValidatableObject` | | Async rules (bureau lookup) | yes, through `ValidateAsync` | attributes are synchronous checks; I/O lookups stay in the handler | | Wiring | a filter per endpoint or group | one service registration; source-generated | | Opt out | do not attach the filter | `.DisableValidation()` on an endpoint | | Failure response | whatever the filter returns | automatic 400 with error details | | Types | FluentValidation 12.1 + DI extensions packages | the `Microsoft.Extensions.Validation` APIs | The built-in source generator only sees types in the calling assembly, so request types in another project need care. Neither mechanism runs the other's rules: `AddValidation` ignores FluentValidation validators, and the filter ignores DataAnnotations unless your validator repeats them. ## Choosing - **Already on FluentValidation, with async or rich rules:** keep the filter; it is small and explicit. - **Simple attribute-level rules and a new service:** the built-in `AddValidation` removes a dependency. - **Both present:** decide which one owns validation for each request type, or clients get two error passes. ## What interviewers listen for - A filter that finds the argument, awaits `ValidateAsync` with `RequestAborted`, and short-circuits with `ValidationProblem`. - Knowing the typed filter is created from `RequestServices`, so scoped validators are safe, unlike a shared instance. - An accurate picture of `AddValidation` in .NET 10 and why it does not replace FluentValidation rules.

  • Why is constructor-injecting a scoped IValidator<T> into the filter safe with AddEndpointFilter<TFilterType>()?
    In ASP.NET Core 10, `AddEndpointFilter<TFilterType>()` registers a factory that creates the filter with `ActivatorUtilities` from `context.HttpContext.RequestServices` on every invocation. Each request therefore gets a filter, and a validator, from its own scope. A filter instance passed to `AddEndpointFilter(filter)` is shared, so it must resolve the validator per request instead.
  • Can you apply the filter to the whole route group instead of each endpoint?
    Yes: `loans.AddEndpointFilter<ValidationFilter<LoanApplication>>()` on the `RouteGroupBuilder` adds it to every endpoint in the group. The pass-through when no `LoanApplication` argument exists keeps GET endpoints in the group unaffected, though each still pays the small cost of the filter running.

  • Built-in AddValidation in .NET 10 also discovers and runs FluentValidation validators.
  • A typed endpoint filter is created once at startup, so it cannot take scoped services.
  • The filter must call next even when validation fails, so the handler can decide.
  • Endpoint filters can only read raw HttpContext, not the bound handler arguments.
  • AddValidation is part of FluentValidation 12's new Minimal API support.

Assumes ASP.NET Core 10: built-in Minimal API validation (AddValidation, DisableValidation) is new in 10; FluentValidation 12.1 has no Minimal API integration of its own, so the filter is hand-written.