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

Time:10-07

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);

CodePudding user response:

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);

CodePudding user response:

Try using , in the URL to replace the commas.

  • Related