将 int 列表传递给 HttpGet 请求 [英] 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;
}
但是,当我对该方法执行 Get 请求时:
However, when I do a Get request for the method:
{{domain}}/Controller/GetValuesForList?listOfIds=1&listOfIds=2
我在调试时收到错误,指出 listOfIds
为空.在我们的控制器中,我们有许多可以正常工作的公共 HttpGet 方法,当将参数更改为单个 int 时,它可以正常工作.我也尝试将参数类型更改为 int[]
和 IEnumerable
,但没有更改.
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.
但是,当更改对 HttpPost 的调用并将列表作为 x-www-form-urlencoded 值传递时,该方法有效.
However, when changing the call to a HttpPost and passing the list as an x-www-form-urlencoded value, the method works.
是否可以将列表传递给 Get 方法,还是必须使用 Post?因为它实际上不是一个 post 方法(因为它返回值的 JSON 模型并且没有任何内容保存到服务器).
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).
推荐答案
如果你使用的是 MVC WebAPI,那么你可以像这样声明你的方法:
If you are using MVC WebAPI, then you can declare your method like this:
[HttpGet]
public int GetTotalItemsInArray([FromQuery]int[] listOfIds)
{
return listOfIds.Length;
}
然后你这样查询:blabla.com/GetTotalItemsInArray?listOfIds=1&listOfIds=2&listOfIds=3
这会将数组 [1, 2, 3] 匹配到 listOfIds 参数中(并按预期返回 3)
this will match array [1, 2, 3] into listOfIds param (and return 3 as expected)
这篇关于将 int 列表传递给 HttpGet 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!