Skip to content

ValidationsGenerator silently skips endpoint handlers passed as delegate variables or parameters #67122

Open

Description

@ANcpLua

Summary

The ValidationsGenerator performs validation discovery by resolving the endpoint handler method at Map* call sites. The resolver, ResolveMethodFromOperation in InvocationOperationExtensions.cs (shared source, linked into Microsoft.Extensions.Validation.ValidationsGenerator.csproj), handles inline lambdas (IAnonymousFunctionOperation), local functions, method groups, and readonly fields — but has no case for IParameterReferenceOperation or ILocalReferenceOperation. A handler passed as a delegate variable or method parameter falls through to _ => null.

For the RequestDelegateGenerator this is benign (it falls back to the runtime RequestDelegateFactory). For the ValidationsGenerator it is not: TryGetRouteHandlerMethod returns false, ExtractValidatableTypes (ValidationsGenerator.TypesParser.cs) gets an empty parameter list, and validation discovery for that endpoint is silently skipped — no diagnostic, no generated ValidatableInfo, validation just doesn't run.

This affects even completely non-generic handlers.

Reproduction

public static class EndpointExtensions
{
    // Handler arrives as a delegate parameter — never resolved by the generator
    public static RouteHandlerBuilder MapCommand<TRequest>(
        this IEndpointRouteBuilder endpoints,
        string pattern,
        Func<TRequest, CancellationToken, Task<IResult>> handler)
        where TRequest : IValidatable
        => endpoints.MapPost(pattern, handler);
}

// Non-generic variant is equally affected:
Func<CreateOrderRequest, Task<IResult>> handler = async req => Results.Ok();
app.MapPost("/orders", handler); // validation silently skipped

Expected Behavior

Either the parameter types are discovered (the ValidationsGenerator only needs the delegate's parameter types, not the method body — when method resolution fails, the delegate type's Invoke signature is sufficient for TryExtractValidatableType), or the generator emits a diagnostic that the handler could not be statically analyzed.

Actual Behavior

Validation discovery is silently skipped for the endpoint.

Notes

Discovered while investigating #65418 / #65419. The repro in #65418 used this delegate-parameter shape; #65419 fixes the ITypeParameterSymbol handling layer (constraint walking + typeof(T) leak into generated code) and is kept scoped to that per review feedback, so the resolver gap is tracked separately here. A fix likely belongs on the Validation generator's side (fallback to the delegate type's Invoke signature) rather than in the shared RDG resolver, to avoid changing RDG behavior.

Activity

  1. added
    area-minimal
    on Jun 10, 2026
  2. added
    feature-validation
    on Jun 10, 2026
  3. self-assigned this
    on Jul 15, 2026
  4. Youssef1313 commented on Jul 15, 2026

    @Youssef1313
    Member

    For this variant:

    Func<CreateOrderRequest, Task<IResult>> handler = async req => Results.Ok();
    app.MapPost("/orders", handler); // validation silently skipped
    
    

    We could make it work.

    For the other variant of MapCommand<TRequest>, we could try to either fallback to runtime reflection, or produce a warning. We prefer to try to runtime reflection approach.

  5. added this to the Backlog milestone on Jul 15, 2026
  6. ANcpLua commented on Aug 20, 2026

    @ANcpLua
    Author

    Thanks for picking this up, confirming the first variant is resolved. Func<CreateOrderRequest, Task<IResult>> handler = ...; app.MapPost("/orders", handler); discovers and validates now, via the DelegateInvokeMethod fallback from #67821.

    On the MapCommand<TRequest> variant: there's an existing workaround that may change how much this needs. Annotating the request type with [ValidatableType] routes it through the attribute-discovery path instead of endpoint discovery, so it lands in the generated resolver regardless of how the endpoint was registered, and the runtime filter then resolves by the actual parameter type, which is closed. Verified on 10.0.400 with the issue's exact shape:

    Repro (single file, dotnet run repro.cs)
    #:sdk Microsoft.NET.Sdk.Web
    #:property JsonSerializerIsReflectionEnabledByDefault=true
    #pragma warning disable ASP0029
    using System.ComponentModel.DataAnnotations;
    using Microsoft.AspNetCore.Routing;
    using Microsoft.Extensions.Validation;
    
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddValidation();
    var app = builder.Build();
    app.MapCommand<CreateOrderRequest>("/orders", (req, ct) => Task.FromResult(Results.Ok()));
    app.Run();
    
    public static class EndpointExtensions
    {
        public static RouteHandlerBuilder MapCommand<TRequest>(
            this IEndpointRouteBuilder endpoints,
            string pattern,
            Func<TRequest, CancellationToken, Task<IResult>> handler)
            => endpoints.MapPost(pattern, handler);
    }
    
    [ValidatableType]   // remove this line and the same POST returns 200
    public class CreateOrderRequest
    {
        [Required, MinLength(3)]
        public string ProductName { get; set; } = string.Empty;
    
        [Range(1, 1000)]
        public int Quantity { get; set; }
    }

    POST {"ProductName":"a","Quantity":5000} returns 400 with both errors as written, and 200 with the attribute removed.

    Why the unannotated case is skipped: endpoint discovery is FindEndpoints, a syntax predicate matching the invoked method name against InvocationOperationExtensions.KnownMethods. app.MapCommand<CreateOrderRequest>(...) doesn't match, so it is never a call site and the closed type argument is never seen. The only site that does match is the inner endpoints.MapPost(pattern, handler), where the handler is still Func<TRequest, CancellationToken, Task<IResult>>. Post-#67821 that resolves, but the resolved parameter type is the open TRequest, which falls out of TryExtractValidatableType, so it fails closed rather than emitting anything broken.

    One wrinkle from #67993 (verified against current main): ASP0034 catches this shape as a side effect: the resolved parameter type is the bare TRequest, whose DeclaredAccessibility is NotApplicable, so IsInaccessibleFromGeneratedCode() treats it as inaccessible and warns:

    ASP0034: The type 'TRequest' of endpoint parameter 'arg1' is not accessible from the generated validation code. The type must be public or internal and must not be a file-local type, otherwise its validation is silently skipped.

    With arg1 as the parameter name (the delegate Invoke method's metadata name) and no source location to anchor it. That's better than silence, but it describes the wrong problem (nothing is inaccessible, the type is open at the only call site the generator sees), and the suggested remedy can't be applied to a type parameter.

    That might reframe the question: rather than a reflection fallback, is the near-term gap that this shape gets either no hint (shipped SDKs) or a misleading one (post-#67993)? Special-casing ITypeParameterSymbol there with a message that says what's actually happening, "the request type can't be resolved statically at this call site; annotate it with [ValidatableType]", would cover generic registration helpers generally, with runtime reflection still open as the fuller answer. Happy to help with either direction.

  7. added
    bug
    on Oct 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-minimalbugfeature-validation

Type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions