C# 将 int 列表传递给 HttpGet 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17021624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing a list of int to a HttpGet request
提问by StormPooper
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:
但是,当我对该方法执行 Get 请求时:
{{domain}}/Controller/GetValuesForList?listOfIds=1&listOfIds=2
I get an error when debugging stating that listOfIdsis 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.
调试时出现错误,指出它listOfIds为空。在我们的控制器中,我们有许多工作正常的公共 HttpGet 方法,当将参数更改为单个 int 时,它可以工作。我也尝试将参数类型更改为int[]and IEnumerable<int>,但没有更改。
However, when changing the call to a HttpPost and passing the list as an x-www-form-urlencoded value, the method works.
但是,当更改对 HttpPost 的调用并将列表作为 x-www-form-urlencoded 值传递时,该方法有效。
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).
是否可以将列表传递给 Get 方法,还是必须使用 Post?因为它实际上不是 post 方法(因为它返回值的 JSON 模型并且没有任何内容保存到服务器)。
采纳答案by Liran Brimer
If you are using MVC WebAPI, then you can declare your method like this:
如果您使用的是 MVC WebAPI,那么您可以像这样声明您的方法:
[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
然后你这样查询:
blabla.com/GetTotalItemsInArray?listOfIds=1&listOfIds=2&listOfIds=3
this will match array [1, 2, 3] into listOfIds param (and return 3 as expected)
这会将数组 [1, 2, 3] 匹配到 listOfIds 参数中(并按预期返回 3)
回答by C.B.
Here's a quick hack until you find a better solution:
在您找到更好的解决方案之前,这是一个快速的技巧:
- use "?listOfIds=1,2,5,8,21,34"
- then:
- 使用“?listOfIds=1,2,5,8,21,34”
- 然后:
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 */
...
回答by 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.
到目前为止,我结合了@oleksii 的评论和@CB 的答案,但使用 TryParse 来处理错误和空检查以使其成为可选参数。
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 hereto use Paramsinstead of Formsand combined that with the suggestion from @C.B. to parse the string values to int.
由于这些值不是从表单传递的,我不得不更改从这里链接到的答案 @oleksii以使用Params而不是Forms将其与来自@CB 的建议相结合以将字符串值解析为 int。
While this allows for the traditional listOfIds=1&listOfIds=2, it still requires converting strings to ints.
虽然这允许使用传统的listOfIds=1&listOfIds=2,但它仍然需要将字符串转换为整数。
回答by Mahesh
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)
现在您有一个可以解析为 int 的 id 列表。 Int32.TryParse(id, out result)
回答by Ogglas
In addition to @LiranBrimer if you are using .Net Core:
除了@LiranBrimer,如果您使用的是 .Net Core:
[HttpGet("GetTotalItemsInArray")]
public ActionResult<int[]> GetTotalItemsInArray([FromQuery]int[] listOfIds)
{
return Ok(listOfIds);
}

