nop
nop

Reputation: 6353

Minimal API - multi-value parameters separated by commas to array of strings

I have query parameters such as /api/items?sizes=m,l,xxl, meaning they are separated by commas. I want to accept them as array of strings ([FromQuery] string[] sizes).

How do I do that? I know how to split the string, the issue is how do I accept string[] and let make sure it knows how to split the string?

string[] sizes = request.Sizes.Split(",", StringSplitOptions.RemoveEmptyEntries);

Upvotes: 0

Views: 1717

Answers (2)

Guru Stron
Guru Stron

Reputation: 142833

Such transformation is not supported even for MVC binders (it will require query string in one of the following formats: ?sizes[0]=3344&sizes[1]=2222 or ?sizes=24041&sizes=24117).

You can try using custom binding:

public class ArrayParser
{
    public string[] Value { get; init; }

    public static bool TryParse(string? value, out ArrayParser result)
    {
        result = new()
        {
            Value = value?.Split(',', StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty<string>()
        };

        return true;
    }
}

And usage:

app.MapGet("/api/query-arr", (ArrayParser sizes) => sizes.Value);

Upvotes: 1

Danny
Danny

Reputation: 506

Try using %2c in the URL to replace the commas.

Upvotes: 0

Related Questions