确保请求中的数据与模型属性匹配,并使用Model Binding来解析请求中的数据。例如:
[HttpPost] public IActionResult AddProduct([FromBody] ProductModel product) { if (!ModelState.IsValid) { return BadRequest(ModelState); }
// Perform operation using product object
return Ok();
}
在上面的代码中,ProductModel是通过Model Binding来解析请求中的JSON数据。事先请确保请求中的所有属性都与ProductModel的属性匹配。如果某个属性在JSON中被忽略,则它将在ProductModel实例中保持为默认值。如果某个属性在JSON中被赋以无效的值,则ModelState将包含核实错误。