Passing a list of int to a HttpGet request

If you are using MVC WebAPI, then you can declare your method like this:

[HttpGet]
public int GetTotalItemsInArray([FromQuery]int[] listOfIds)
{
       return listOfIds.Length;
}

and then you query like this: blabla.com/GetTotalItemsInArray?listOfIds=1&listOfIds=2&listOfIds=3

this will match array [1, 2, 3] into listOfIds param (and return 3 as expected)


Here's a quick hack until you find a better solution:

  • use "?listOfIds=1,2,5,8,21,34"
  • then:
GetValuesForList(string listOfIds)
{
    /* [create model] here */
    //string[] numbers = listOfIds.Split(',');
    foreach(string number in listOfIds.Split(','))
        model.Add(GetValueForId(int.Parse(number))
    /* [create response for model] here */
    ...

In addition to @LiranBrimer if you are using .Net Core:

[HttpGet("GetTotalItemsInArray")]
public ActionResult<int[]> GetTotalItemsInArray([FromQuery]int[] listOfIds)
{
       return Ok(listOfIds);
}