3

I would like to know how we can design .net core api controller to accept an array value like given below

http://localhost:32656/api/Values?str[]="abc"&str[]="xyz"

I did some research online and the only two options, I was able to find is either I need to pass indexes inside the array eg:- http://localhost:32656/api/Values?str[0]="abc"&str[1]="xyz" (Pass indexes inside the array)

or I need to pass the array as repeated query strings. eg:- http://localhost:32656/api/Values?str="abc"&str="xyz" (Pass it as repeated query strings)

But I would like to see the other possible options to send an array to .net core 2.1 api controller.

2 Answers 2

3

You can take advantage of the FromQuery attribute here, specifying the Name property as str[]:

public IActionResult Values([FromQuery(Name = "str[]")] List<string> strValues)
{
    ...
}

If you also want to strip out the "s for each value, you can use a Select. Here's a an example:

public IActionResult Values([FromQuery(Name = "str[]")] List<string> strValues)
{
    var strValuesWithoutQuotes = strValues.Select(x => x.Trim('"'));

    ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

Here is how we do it:

[Route("api/v1/[controller]")]
public class TestController : Controller
{
    [HttpGet]
    public async Task Get(List<string> stringValues)
    {
        ...
    }
}

Then call the endpoint with http://localhost/api/v1/test?stringValues=string1&stringValues=string2

stringValues should have the list of values in the query string

3 Comments

Thanks Cale for the quick reply. This is how I am currently doing. But I need to change the api call in to this format. localhost:32656/api/…" . I need to add square brackets in to the URL. Thanks.
are you unable to update the calling system? I haven't seen that url syntax before, and I am not sure .net core will support it
Unfortunately I am not able to change the calling system. Thanks for your support. Have a great day.

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.