c# - 在 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 请求传递/处理多个参数的正确方法是什么?
解决方案
我认为如果您明确提到要从查询字符串中读取变量,它将在您描述的方法中正常工作:
//.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
推荐阅读
- javascript - Google Maps JavaScript API 警告:NoApiKeys - 仅在 Safari 中
- mysql - MySQL(5.7) 不提示我有关 root db 密码
- python - 添加一个 for 循环作为键,另一个 for 循环作为值
- linux - 如何在 buildspec.yml 中处理输入(是/否)
- android - React Native“Gradle 构建失败并出现异常”
- java - getInputStream() 在设备上非常慢,但在模拟器上没有
- javascript - 三个js解决黑色模型和关闭bump
- javascript - JQuery小册子添加搜索栏
- visual-studio - 代码无法访问 - Visual Studio 中的 React Native
- unity3d - 为什么我的测试视频广告无法在 Android 上运行,但在编辑器上运行?