首页 > 解决方案 > 在 C# 中的 HTTP Get 请求中传递可变数量的多个参数

问题描述

我正在尝试创建一个 Web API。作为其中的一部分,我想创建一个 Get 方法,它可以接受任意数量的特定类型的变量。

public class MyController : ControllerBase
    {
        [HttpGet]
        public int[] Get(int[] ids)
        {

            for(int i = 0; i < ids.Length; i++)
            {
                ids[i] = ids[i] * 100;
            }

            return ids;
        }
    }

当我尝试使用邮递员发出获取请求时

https://localhost:44363/api/executionstatus?ids=1&ids=2&ids=3

我收到一个错误

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"出现一个或多个验证错误。","status":400,"traceId" :"|39f5d965-4240af31edd27f50.","errors":{"$":["JSON 值无法转换为 System.Int32[]。路径:$ | LineNumber: 0 | BytePositionInLine: 1."]}}

我也试过

https://localhost:44363/api/executionstatus?ids=1,2,3

但它也会导致同样的错误。从 get 请求传递/处理多个参数的正确方法是什么?

标签: c#asp.net-web-apihttprequesthttp-getwebapi

解决方案


我认为如果您明确提到要从查询字符串中读取变量,它将在您描述的方法中正常工作:

//.net Core
public int[] Get([FromQuery]int[] ids)

//.net Framework
public int[] Get([FromUri]int[] ids)

来电:

https://localhost:44363/api/executionstatus?ids=1&ids=2&ids=3

推荐阅读