Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a list of int to a HttpGet request

I have a function similar in structure to this:

[HttpGet]
public HttpResponseMessage GetValuesForList(List<int> listOfIds)
{
    /* create model */        

    foreach(var id in listOfIds)
        model.Add(GetValueForId(id)

    /* create response for model */
    return response;
}

However, when I do a Get request for the method:

{{domain}}/Controller/GetValuesForList?listOfIds=1&listOfIds=2

I get an error when debugging stating that listOfIds is null. In our controller we have a number of public HttpGet methods that work fine, and when changing the parameter to a single int it works. I've tried changing the parameter type to int[] and IEnumerable<int> too, but no change.

However, when changing the call to a HttpPost and passing the list as an x-www-form-urlencoded value, the method works.

Is it possible to pass a list to a Get method, or will I have to use Post? Since it's not actually a post method (as it returns a JSON model of values and nothing is saved to the server).

like image 240
StormFoo Avatar asked Jun 10 '13 10:06

StormFoo


3 Answers

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)

like image 131
Liran Brimer Avatar answered Nov 20 '22 02:11

Liran Brimer


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 */
    ...
like image 43
C.B. Avatar answered Nov 20 '22 02:11

C.B.


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

[HttpGet("GetTotalItemsInArray")]
public ActionResult<int[]> GetTotalItemsInArray([FromQuery]int[] listOfIds)
{
       return Ok(listOfIds);
}
like image 4
Ogglas Avatar answered Nov 20 '22 01:11

Ogglas