0

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);
coder
  • 151
  • 1
  • 13
nop
  • 4,711
  • 6
  • 32
  • 93
  • Check this link for answers:https://stackoverflow.com/questions/43397851/pass-array-into-asp-net-core-route-query-string – D A Oct 06 '22 at 08:14
  • @DA, I know. However `?values=this&values=that` is not a solution to my use case. – nop Oct 06 '22 at 08:37

2 Answers2

1

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);
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • Thank you very much! Is it going to be `app.MapGet("/api/query-arr", ([FromQuery] ArrayParser? sizes) => sizes?.Value);` for optional query parameter? – nop Oct 06 '22 at 12:33
  • Actually, it appears to be wrong in swagger. `{ "value": [ "string" ] }`, like it is not an input field that I can input `item1,item2` – nop Oct 06 '22 at 12:52
  • 1
    @nop yes. It should have been fixed by [this pr](https://github.com/dotnet/aspnetcore/pull/36526) in .NET 7 but it seems that it still does not work. – Guru Stron Oct 06 '22 at 13:48
  • 1
    @nop see the update, `FromQuery` is not needed, removing it fixes the swagger. – Guru Stron Oct 06 '22 at 13:53
0

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

Danny
  • 317
  • 4
  • 17
  • This is not relevant to the question. I can pass anything in queries. The thing is how do I handle it inside the minimal API, so it accepts `[FromQuery] string[] sizes` – nop Oct 06 '22 at 07:02