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);
2
  • Check this link for answers:stackoverflow.com/questions/43397851/… Commented Oct 6, 2022 at 8:14
  • @DA, I know. However ?values=this&values=that is not a solution to my use case. Commented Oct 6, 2022 at 8:37

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very much! Is it going to be app.MapGet("/api/query-arr", ([FromQuery] ArrayParser? sizes) => sizes?.Value); for optional query parameter?
Actually, it appears to be wrong in swagger. { "value": [ "string" ] }, like it is not an input field that I can input item1,item2
@nop yes. It should have been fixed by this pr in .NET 7 but it seems that it still does not work.
@nop see the update, FromQuery is not needed, removing it fixes the swagger.
0

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

1 Comment

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

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.