how we can design .net core api controller to accept an array value of strings

Viewed 161

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

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('"'));

    ...
}

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

Related