【问题标题】:Cannot send a collection of integers to a Web Core Api Post method, it is set to null无法将整数集合发送到 Web Core Api Post 方法,它设置为 null
【发布时间】:2017-11-26 22:34:13
【问题描述】:

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

方法是;

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

这只是为了测试,我在return语句上放了一个断点,inspectionIds的payload是null

在 Postman 我有

编辑:我刚刚从签名中删除了方括号。我尝试了IEnumerable&lt;int&gt;int[],但都没有成功

【问题讨论】:

  • 我猜JSON应该是{ "inspectionIds": [11111111, 11111112] }?您正在发送字符串数组,但控制器需要整数集合。

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


【解决方案1】:

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

还有IEnumerable&lt;int&gt;[]代表集合的集合,比如

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

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

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

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

[11111111, 11111112]

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

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

并相应地更新操作

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

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

{ "inspectionIds": [11111111, 11111112] }

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

【讨论】:

    【解决方案2】:

    我认为问题出在:IEnumerable&lt;int&gt;[] - 它是整数列表数组?

    应该是简单的int[](也可以是IEnumerable&lt;int&gt;)。

    【讨论】:

    • 抱歉,您在我的问题中发现了错误。我已经尝试了您的两种选择,结果相同。
    • 在这种情况下,它必须在不需要额外模型的情况下工作,但是......我之前没有抓住它 - 动作签名中的变量名称并不重要,只是你的 json 对象必须适合 c# 类型,所以如果你想得到int[] xxx,那么只需直接发送一个整数数组[11111111, 11111112],而不用像这里{ "xxx": [11111111, 11111112] }那样将它包装在一个额外的json对象中。
    猜你喜欢
    • 1970-01-01
    • 2015-10-07
    • 2018-04-27
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多