c# - 无法将整数集合发送到 Web Core Api Post 方法,它被设置为 null

标签 c# asp.net-core .net-core postman asp.net-core-webapi

我想将整数集合发送到网络核心 api 上的 post 方法。

方法是;

[HttpPost("open")]
public IActionResult OpenInspections([FromBody]IEnumerable<int> inspectionIds)
{
    return NoContent();
//...

这只是为了测试,我在 return 语句和 inspectionIds 上放置了一个断点有效载荷是 null .

在 Postman 中我有

enter image description here

编辑:我刚刚从签名中删除了方括号。我正在尝试 IEnumerable<int>int[]但都没有用

最佳答案

它是空的,因为发布的内容和 Action 所期望的不匹配,所以它在发布时不绑定(bind)模型。发送的示例数据具有 string数组 ["11111111", "11111112"]而不是 int数组 [11111111, 11111112] ,

还有IEnumerable<int>[]代表集合的集合,比如

{ "inspectionIds": [[11111111, 11111112], [11111111, 11111112]]}

要获得所需的行为,可以更新操作以期望所需的数据类型

[HttpPost("open")]
public IActionResult OpenInspections([FromBody]int[] inspectionIds) {
    //...
}

确保发布的正文也符合预期

[11111111, 11111112]

考虑使用具体模型,因为所提供问题中的发布数据是 JSON 对象

public class Inspection {
    public int[] inspectionIds { get; set; }
}

并相应地更新 Action

[HttpPost("open")]
public IActionResult OpenInspections([FromBody]Inspection model) {
    int[] inspectionIds = model.inspectionIds;
   //...
}

模型还必须与发布的预期数据相匹配。

{ "inspectionIds": [11111111, 11111112] }

请注意,如果所需的 ID 假定为 int然后不要将它们用引号引起来。

关于c# - 无法将整数集合发送到 Web Core Api Post 方法,它被设置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44719852/

相关文章:

c# - Blazor WebAssembly 401 未经授权,即使我已获得授权

c# - 如何从 Windows 窗体创建 EXE 文件?

c# - 如何使用 ASP.Net vNext/5 登录到输出窗口

c# - 如何使用.Net Core验证KeyCloak提供的JWT?

visual-studio - 分析器在 .NET Core 项目中有黄色三角形

c# - 为什么运行时表达式会导致 Entity Framework Core 5 的缓存发生冲突?

c# - 摆脱滚动列表框中的额外空间

c# - 使用 HttpRequestMessage 或 Stream 上传 REST 文件?

json - NU1001 无法解析依赖项 Microsoft...>=1.0.0

c# - 访问 .net 核心中的 IServiceProvider/容器