DamianEdwards / MinimalApis.Extensions

A set of extensions and helpers for working with ASP.NET Core Minimal APIs.
MIT License
293 stars 27 forks source link

.WithParameterValidation() does not work with [FromRoute] parameters #46

Open JCKortlang opened 3 months ago

JCKortlang commented 3 months ago
        //Should fail when id does not equal "hello" or "world". Expect 400 response
        builder.MapGet("/test/{id}", async ([FromRoute, RegularExpression("^(hello|world)$")] string id) =>
        {   
            //Currently returns "hello world" regardless of validation
            return Results.Ok("hello world");
        }).WithParameterValidation();
DamianEdwards commented 2 months ago

Validating parameters that are simple types is not supported currently. This is similar to how ModelValidation in ASP.NET Core MVC works. You need to accept parameters that are complex types whose properties have the validation attributes on them. You can combine a complex type with AsParameters to achieve what you want:

// Will fail when id does not equal "hello" or "world". Expect 400 response
builder.MapGet("/test/{id}", async ([AsParameters] TestReuqest request) =>
{   
    // Will only return if properties of `request` are valid
    return Results.Ok("hello world");
}).WithParameterValidation();

public class TestRequest
{
    [FromRoute, RegularExpression("^(hello|world)$")]
    public string? Id { get; set; }
}