skip to content

In ASP.NET Core 10, Program.cs calls AddValidation, yet a reservation body's property rules never fire for endpoints mapped in a separate class library. Why, and how do you fix it?

level: seniorimportance: should knowfreq 30%

answer

  1. build-time metadata, not reflection
  2. the assembly that calls AddValidation
  3. Map* calls and [ValidatableType] in that source
  4. public types only
  5. no exception, no log line

basics

~20 s

Type metadata comes from a source generator that scans only the assembly calling AddValidation; the library's endpoints were never seen, so their body types are skipped silently. Call AddValidation from the library too, and keep validated types public.

solid answer

~50 s

`AddValidation` relies on a Roslyn source generator. In the compilation that contains the `AddValidation()` call, it finds the `Map*` endpoint invocations and the types marked `[ValidatableType]`, emits a `ValidatableTypeInfo` for each validatable public type, and intercepts that `AddValidation` call to insert the generated resolver into `ValidationOptions.Resolvers`. At run time the only other resolver reads attributes placed directly on handler parameters; it knows nothing about properties. So when the booking endpoints are mapped in a class library that never calls `AddValidation`, the filter still runs, a `[Range]` on a query parameter still works, but the body type's property rules have no metadata and are skipped, with no exception and no log entry. The fix is an extension method in the library that calls `services.AddValidation()` (referencing the `Microsoft.Extensions.Validation` package if the library uses the plain SDK), called from `Program.cs` beside the host's own `AddValidation()`.

code

csharp · 19 lines
csharp
// Rail.Booking.Endpoints (class library)
// usings for Microsoft.AspNetCore.* and Microsoft.Extensions.DependencyInjection omitted

public static class BookingModule
{
    public static IServiceCollection AddBookingValidation(this IServiceCollection services)
        => services.AddValidation();   // the generator runs in this assembly

    public static IEndpointRouteBuilder MapBooking(this IEndpointRouteBuilder app)
    {
        app.MapPost("/reservations", (SeatReservation reservation) => TypedResults.Ok());
        return app;
    }
}

// Program.cs (host)
builder.Services.AddBookingValidation();
builder.Services.AddValidation();         // the host's own endpoints and types
app.MapBooking();

go deeper

for a junior

Recall that AddValidation's type metadata is generated at build time and only for the project where AddValidation is called.

for a middle

Explain the two resolvers, what the generator scans, and why parameter attributes keep working while body properties go unchecked.

for a senior

Diagnose silent validation gaps in modular solutions: per-assembly AddValidation registration, public DTOs, [ValidatableType] for undiscovered roots, and a test that proves each module rejects invalid input.

for a principal

Set the solution-wide rule for where request contracts and their registration live, so every module that maps endpoints owns its validation registration and gaps cannot hide.

## Two resolvers, two sources of truth `ValidationOptions.Resolvers` holds the objects the validation filter asks "what can I validate here?": | Resolver | Added by | Knows about | |---|---|---| | runtime parameter resolver | every `AddValidation()` call | validation attributes placed directly on a handler parameter, read by reflection | | generated resolver | the source generator, through an intercepted `AddValidation()` call | the validatable properties of request types, nested types and collection item types | The runtime resolver deliberately answers "no" for every type, so **all property-level validation depends on generated metadata**. ## What the generator sees The generator runs inside one compilation, the project that contains the `AddValidation()` call, and only emits code when it finds that call. In that project's source it collects: 1. the parameter types of every `MapGet`, `MapPost`, `MapPut`, `MapPatch`, `MapDelete`, `MapMethods`, `Map` and `MapFallback` handler it can resolve, skipping services; 2. every type marked `[ValidatableType]`; 3. everything reachable from those: property types, collection item types, base types and `[JsonDerivedType]` subtypes. Only **public** types are emitted, because the generated code must be able to refer to them. The output, a `ValidatableInfoResolver.g.cs` file, defines the type metadata and an interceptor for that project's `AddValidation()` call that inserts the generated resolver at the front of `Resolvers`. ## Why the library's endpoints are not covered In the rail-booking solution, `Rail.Booking.Endpoints` maps `POST /reservations` in a `MapBooking()` extension method and `Program.cs` calls `builder.Services.AddValidation()`: - The generator runs in the host project, but the `MapPost` call lives in the library's source, so `SeatReservation` is never discovered from the host. - At run time the endpoint still gets the validation filter (resolvers exist), so parameter attributes such as `[Range(1, 12)] int carriage` are enforced. - `SeatReservation` has no generated metadata, so `TrainNumber` and every passenger rule are skipped. - Nothing throws and nothing is logged; invalid reservations simply reach the handler. ## The fix 1. In the library, add a registration method that calls `services.AddValidation()`, so the generator runs in that compilation and emits metadata for its endpoints and types. 2. If the library uses the plain `Microsoft.NET.Sdk`, reference the `Microsoft.Extensions.Validation` package so the generator is available there. 3. Call the library's method from `Program.cs` alongside the host's own `AddValidation()`; each call contributes its generated resolver. 4. Make the request types `public`; an `internal` DTO is skipped silently in either assembly. 5. For a root type that no `Map*` signature exposes, mark it `[ValidatableType]`; in .NET 10 that attribute is experimental and raises ASP0029, which a plain library suppresses with `<NoWarn>$(NoWarn);ASP0029</NoWarn>`. ## Catching it before production - Add an integration test that posts an invalid body to each module's endpoints and expects 400; this is the only signal, since the failure mode is silence. - Set `<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>` to inspect `ValidatableInfoResolver.g.cs` and confirm which types were emitted. ## What interviewers listen for - That validation metadata is produced at build time per assembly, not discovered by reflection at run time. - The silent failure mode and why parameter attributes still work. - The registration-per-assembly fix, the public-type rule and the role of `[ValidatableType]`.

  • Why does a [Range] on a query parameter still work in the library's endpoint when the body rules do not?
    Parameter attributes are handled by the runtime resolver that every `AddValidation()` call registers; it reads them by reflection when the endpoint is built. Property rules need the generated `ValidatableTypeInfo`, which exists only for types the generator discovered in an assembly that calls `AddValidation()`.
  • A request DTO is declared internal in the host project itself. Is it validated?
    No. The generator emits metadata only for public types, so an internal body type is skipped just as silently as one from an uncovered library. Make the DTO public, or the property rules never run even though `AddValidation()` is called in the same project.

  • AddValidation discovers validatable types by reflection over all loaded assemblies at startup.
  • A missing type metadata entry makes AddValidation throw at startup.
  • Adding InternalsVisibleTo lets the generator validate internal DTOs.
  • Calling AddValidation once in Program.cs covers endpoints mapped in every referenced library.
  • Setting ValidationOptions.MaxDepth higher makes the library's types validate.

Assumes ASP.NET Core 10: the AddValidation source generator, its per-assembly scope and the experimental [ValidatableType] (ASP0029) are the .NET 10 behaviour.