1

I'm trying to get my simple ASP.NET Core 7 minimal API to automatically bind the QueryString parameters into a single POCO.

Reference: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis/parameter-binding?view=aspnetcore-7.0

For example:

https://localhost:5000/some/endpoint?a=1&b=hello&c=true

public record Query(int? A, string? B, bool? C); // Notice how all are optional!

public static async Task<Ok<List<Result>>> HandleAsync(
    Query query,
    MyDbContext myDbContext,
    HttpContext context,
    CancellationToken cancellationToken
)
{ .. }

If I do that, the framework is thinking/expecting the Query item to be [FromBody]. I've also tried this

[FromQuery] Query query,

but that also didn't work. (Unless I did something wrong).

Of course, this would work:

public static async Task<Ok<List<Result>>> HandleAsync(
    int? a,
    string? b,
    bool? c,
    MyDbContext myDbContext,
    HttpContext context,
    CancellationToken cancellationToken
)

but I don't want/like that. What can I try next?

2

2 Answers 2

2

Use AsParametersAttribute:

AsParametersAttribute enables simple parameter binding to types and not complex or recursive model binding.

public static async Task<Ok<List<Result>>> HandleAsync(
    [AsParameters] Query query,
    MyDbContext myDbContext,
    HttpContext context,
    CancellationToken cancellationToken
)
{
    ... 
}
Sign up to request clarification or add additional context in comments.

2 Comments

and this should work when Query is a record ? also, Query is a "flat" record .. meaning all simple Types. no custom/complex classes as the properties.
@Pure.Krome I have tested it with record (from your question).
0

If you change record to class it should work.

public class Query
{
    public int? A { get; set; }
    public string? B { get; set; }
    public bool? C { get; set; }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.