Passing a list of int to a HttpGet request

落花浮王杯 提交于 2019-12-03 02:31:12
Liran Brimer

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

[HttpGet]
public int GetTotalItemsInArray([FromUri]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 */
    ...
StormPooper

So far I have a combination of the comment by @oleksii and the answer from @C.B, but using TryParse to deal with errors and a null check to make it an optional parameter.

var paramValues = HttpContext.Current.Request.Params.GetValues("listOfIds");
if (paramValues != null)
{
   foreach (var id in paramValues)
   {
        int result; 
        if (Int32.TryParse(id, out result))
            model.Add(GetValueForId(Add(result));
        else
           // error handling
    }
}

Since the values are not passed from a form I had to change the answer @oleksii linked to from here to use Params instead of Forms and combined that with the suggestion from @C.B. to parse the string values to int.

While this allows for the traditional listOfIds=1&listOfIds=2, it still requires converting strings to ints.

You can also pass the serialized array in the request string on client and deserialize on server side:

var listOfIds = [1,2,3,45];
var ArrlistOfIds = JSON.stringify(listOfIds);

For the query string:

"MyMethod?listOfIds=" + ArrlistOfIds

And then in the server side, just deserialize:

public ActionResult MyMethod(string listOfIds = null)
{
    List<string> arrStatus = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<string[]>(arrStatusString).ToList();
    .......
}

Now you have a list of ids that could be parsed to int. Int32.TryParse(id, out result)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!