在 ASP.Net Core 5 MVC Controller 中,当传递包含小数的 JSON 对象 FromBody 时,模型始终为 null

In ASP.Net Core 5 MVC Controller, when passed a JSON object FromBody that contains a decimal the model is always null

传入此 json 有效:

{
  "products": [
    {
      "barcode": "1",
      "quantity": 1,
      "name": "Barratt Fruit Salad Chews 400 pc box",
      "unitPrice": 8,
      "totalPrice": 8,
      "isInBuyTwoGetOneFreePromotion": false
    }
  ]
}

传入此 json 无效:

{
  "products": [
    {
      "barcode": "8",
      "quantity": "4",
      "name": "Bonds dinosaurs",
      "unitPrice": 0.5,
      "totalPrice": 2,
      "isInBuyTwoGetOneFreePromotion": true
    }
  ]
}

原因是传递了小数。

我的控制器有这个方法

[HttpPost]
        public async Task<JsonResult> UpdateStockAndLogInvoice([FromBody] Invoice invoice)

它引用了这个模型:

public partial class Invoice
    {
        [JsonProperty("products")]
        public List<InvoiceItem> Products { get; set; }
    }

    public partial class InvoiceItem
    {
        [JsonProperty("barcode")]
        public string Barcode { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("quantity")]
        public int Quantity { get; set; }

        [JsonProperty("totalPrice")]
        public long TotalPrice { get; set; }

        [JsonProperty("unitPrice")]
        public long UnitPrice { get; set; }

        [JsonProperty("isInBuyTwoGetOneFreePromotion")]
        public bool IsInBuyTwoGetOneFreePromotion { get; set; }
    }

我认为问题在于从 javascript 中使用的 float 转换为 C# 中使用的 long,但我已经搜索了 Internet 并且无法弄清楚如何让我的模型被传递而不是空。

感谢接受任何建议!

您的失败 JSON 与您的 InvoiceItem class 至少在两个方面不兼容:

  • Quantity 不是字符串。
  • UnitPrice 是长整数,不能接受浮点数。

在请求处理期间,MVC 模型绑定器尝试将 JSON 主体反序列化为请求的 InvoiceItem 类型,但失败了。它将此失败视为主体为空,检查您是否告诉它允许空主体(默认情况下这样做)并继续,就好像没有提供主体一样。

要解决此问题,您需要解决客户端和服务器端模型之间的差异。由于 JavaScript 确实不关心类型,因此您必须特别小心以确保正确管理客户端数据,否则它不会在服务器端正确反序列化。不同的 ASP.NET MVC 版本在自动处理翻译时可能有不同的限制,但与您的模型匹配的有效 JSON 将始终有效。

所以...更新您的服务器端模型以对 UnitPriceTotalPrice 属性使用十进制,然后修复您的客户端 javascript 以放入正确的值类型。