【问题标题】:Obtaining an IEnumerable from HttpPost从 HttpPost 获取 IEnumerable
【发布时间】:2019-02-17 10:08:47
【问题描述】:

我正在尝试从 HttpPost 请求创建一个 IEnumerable。

正文中的 JSON 内容如下:

[{"id":15496,"order":0},{"id":15500,"order":1},{"id":15503,"order":2}]

post 请求是这样的:

    [HttpPost("[action]")]
    public IActionResult SendReorderRows([FromBody] IEnumerable<ReorderRow> rows){
         foreach(var row in rows){
             Debug.WriteLine(row.id);
         }
    }

引用的类在这里:

    public class ReorderRow
    {
        public int id;
        public int order;
    }

但是当我运行这个例子时,它给了我

对象引用未设置为对象的实例

“行”错误。

我很难找到解析 JSON 并将其转换为 IEnumerable 以在 API 中使用的基本方法。我错过了一些简单的东西吗?

【问题讨论】:

    标签: json asp.net-core-webapi


    【解决方案1】:

    改为使用数组。

    [HttpPost("[action]")]
    public IActionResult SendReorderRows([FromBody] ReorderRow[] rows) {
         foreach(var row in rows){
             Debug.WriteLine(row.id);
         }
    }
    

    它将绑定到 JSON 数组。

    您还需要对象模型中的公共属性,以便在绑定对象时正确填充它们。

    public class ReorderRow {
        public int id { get; set; }
        public int order { get; set; }
    }
    

    参考Model Binding in ASP.NET Core : How model binding works

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多