无法将一组整数发送到Web Core Api Post方法,它被设置为null

ara*_*333 5 c# postman .net-core asp.net-core asp.net-core-webapi

我想将一个整数集合发送到web核心api上的post方法.

方法是;

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

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

在Postman我有

在此输入图像描述

编辑:我刚从签名中删除了方括号.我试图既IEnumerable<int>int[],但都没有成功

Nko*_*osi 10

它为null,因为发布的内容和操作所期望的内容不匹配,因此在发布时不会绑定模型.发送的示例数据有一个string数组["11111111", "11111112"]而不是int数组[11111111, 11111112],

IEnumerable<int>[]代表了一系列集合,比如

{ "inspectionIds": [[11111111, 11111112], [11111111, 11111112]]}
Run Code Online (Sandbox Code Playgroud)

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

[HttpPost("open")]
public IActionResult OpenInspections([FromBody]int[] inspectionIds) {
    //...
}
Run Code Online (Sandbox Code Playgroud)

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

[11111111, 11111112]
Run Code Online (Sandbox Code Playgroud)

要么

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

public class Inspection {
    public int[] inspectionIds { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

并相应地更新操作

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

该模型还必须匹配发布的预期数据.

{ "inspectionIds": [11111111, 11111112] }
Run Code Online (Sandbox Code Playgroud)

请注意,如果想要所需的ID,int则不要将它们用引号括起来.