首页 > 解决方案 > 在 ASP.Net Core 5 MVC 控制器中,当传递一个包含小数的 JSON 对象 FromBody 时,模型始终为空

问题描述

传入这个 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 ,但是我已经搜索了互联网并且无法弄清楚如何让我的模型被传入不为空。

任何建议都将不胜感激!

标签: javascriptc#asp.net.net-coremodel-binding

解决方案


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

  • Quantity不是字符串。
  • UnitPrice很长,它不能接受浮点值。

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

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

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


推荐阅读