【问题标题】:Web API 2 multiple nested modelsWeb API 2 多个嵌套模型
【发布时间】:2023-03-16 12:25:01
【问题描述】:

我正在创建一个网络服务,可以在其中发布多行的新订单。

模型

public class Order {

    public int OrderID { get; set; }
    public string Description { get; set; }
    public string Account { get; set; }
    public ICollection<OrderLine> OrderLine { get; set; }

}

public class OrderLine {
    public int OrderLineID { get; set; }
    public int OrderID { get; set; }
    public string Product { get; set; }
    public double Price { get; set; }
}

控制器

public class OrderController : ApiController
{
    [HttpPost]
    public string Create(Order order)
    {
        OrderRepository or = new OrderRepository();

        return "Foo";
    }
}

使用 Postman,我在 Json 中创建一个发布请求,如下所示:

{"Description" : "Abc", "Account" : "MyAccount",
    "OrderLine[0]" : {
        "ItemCode": "Item1",
        "Price" : "10"
    } 
}

当我在 Visual Studio 中运行调试器时,Order 模型从请求中填充,但 OrderLine 为 NULL。当我改变时

public ICollection<OrderLine> OrderLine {get; set;}

public OrderLine OrderLine {get; set;}

还有我在 Postman 中的 Json 字符串到

{"Description" : "Abc", "YourReference" : "yourABC", "Account" : "AB1010",
    "OrderLine" : {
        "ItemCode": "Item1",
        "Price" : "10"
    }
}

当我发布数据时,我的模型会被填充。我想发布 OrderLines 的集合。我做错了什么?

【问题讨论】:

    标签: asp.net-web-api2 model-binding


    【解决方案1】:

    您正在发布一个OrderLine 数组,因此您的请求需要包含一个数组:

    "OrderLine" : [{}, {}]
    

    它应该是这样的:

    {"Description" : "Abc", "YourReference" : "yourABC", "Account" : "AB1010",
        "OrderLine" : [{
            "ItemCode": "Item1",
            "Price" : "10"
        },
       {
            "ItemCode": "Item2",
            "Price" : "20"
        }]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-10
      • 1970-01-01
      • 2014-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      • 2016-06-29
      相关资源
      最近更新 更多