添加[FromBody]后仍无法读取请求体,POST/PUT API复杂参数为空
问题解决:POST/PUT API无法接收复杂参数
问题描述
我尝试创建一个读取请求体的简单Post API,用Postman调试时发现POST和PUT接口的复杂参数都为空(PUT的id能正常接收)。
代码示例
模型类
public class Model { int BusinessEntityID { get; set; } string NationalIDNumber { get; set; } }
控制器代码
[Route("api/[controller]")] [ApiController] public class EmployeeRegController : ControllerBase { [HttpPost] public IActionResult Post([FromBody] Model createEmpModel) { if (!ModelState.IsValid) { return BadRequest(ModelState); } _employee.EmployeeCreate(createEmpModel); return Ok(new { Message = "Employee created" }); } [HttpPut("{id}")] public IActionResult Put(int id, [FromBody] Model updateEmp) { _employee.EmployeeUpdate(id, updateEmp); return Ok(new { Message = "Employee updated" }); } }
请求JSON
{ "BusinessEntityID": 6, "NationalIDNumber": "658797903" }
已尝试的无效方案
- 移除
[ApiController] - 添加/移除
[FromBody] - 修改请求头
Content-Type - 确认模型与JSON字段名一致
解决方案
问题出在模型类的访问修饰符:C#中类的属性默认是private,而JSON序列化器只能访问public成员,无法读取私有属性,导致参数绑定失败。
只需把模型的属性改为public即可:
public class Model { public int BusinessEntityID { get; set; } public string NationalIDNumber { get; set; } }
修改后重新调试,请求体的参数就能正常绑定到Model对象中了。
内容的提问来源于stack exchange,提问作者Yatender
相关产品推荐
相关产品推荐

