javascript - 在 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 ,但是我已经搜索了互联网并且无法弄清楚如何让我的模型被传入不为空。
任何建议都将不胜感激!
解决方案
InvoiceItem
您失败的 JSON至少在两个方面与您的课程不兼容:
Quantity
不是字符串。UnitPrice
很长,它不能接受浮点值。
在请求处理期间,MVC 模型绑定器尝试将 JSON 主体反序列化为请求的InvoiceItem
类型并失败。它将这种失败视为主体是空的,检查您是否告诉它允许空主体(默认情况下它会这样做)并继续,就好像没有提供任何主体一样。
要解决此问题,您需要解决客户端和服务器端模型之间的差异。由于 JavaScript 真的不关心类型,因此您必须特别小心以确保正确管理客户端数据,否则它不会在服务器端正确反序列化。不同的 ASP.NET MVC 版本在自动处理翻译时可能有不同的限制,但与您的模型匹配的有效 JSON 将始终有效。
UnitPrice
所以...更新您的服务器端模型以对and属性使用十进制TotalPrice
,然后修复您的客户端 javascript 以放入正确的值类型。
推荐阅读
- python - 如何使字段可选?DRF
- amazon-web-services - 尝试将文件上传到 S3 存储桶时如何修复 InvalidArgument 错误 400?
- python - 关于在波斯真实国家网站(sheypoor)中抓取位置标签
- python - 终端中的 Scrapy shell 忽略 runner.py
- snowflake-cloud-data-platform - Snowpipe:仅加载第一行
- python - 转置并保存一列熊猫数据框
- python - 使用特殊规则过滤 django 中的对象
- python - Matplotlib:subplot2grid 中绘图外的颜色条
- javascript - 添加 chech/uncheck all 以过滤控制复选框输入
- javascript - 反应中的jQuery数据表分页