.NET Core 7 WebAPI中FromBody模型绑定为空问题及方案咨询
解决.NET Core 7 WebAPI模型绑定为空的问题
针对你遇到的InvoiceDto对象绑定后为空的问题,可通过以下步骤解决:
1. 替换序列化特性
.NET Core 7默认使用System.Text.Json作为JSON序列化器,你代码中使用的[JsonProperty]属于Newtonsoft.Json的特性,与默认序列化器不兼容,导致属性映射失败。将特性替换为System.Text.Json.Serialization命名空间下的[JsonPropertyName]:
using System.Text.Json.Serialization; public class InvoiceDto { [JsonPropertyName("buyer")] public Buyer? Buyer { get; set; } } public class Buyer { [JsonPropertyName("buyer_vat")] public string? BuyerVat { get; set; } }
2. 确认请求Content-Type
确保请求头的Content-Type设置为application/json,Swagger通常会自动添加该头,但手动调用接口时需注意配置,否则模型绑定会失效。
3. 检查模型绑定错误
在Action中添加模型状态验证,可快速定位绑定失败的具体原因:
[HttpPost] [Route(nameof(UploadSalesInvoice))] public async Task<IActionResult> UploadSalesInvoice([FromBody] InvoiceDto content, [FromQuery]string requestId = "007", long apiKeyId = 1, [FromQuery]string sendToCir = "Auto") { if (!ModelState.IsValid) { return BadRequest(ModelState); } // 后续业务逻辑 }
执行以上操作后,重新测试接口,模型即可正常绑定请求内容。
内容的提问来源于stack exchange,提问作者lonelydev101
相关产品推荐
相关产品推荐

