问题描述: 在ASP.NET Core Web API中,无法接收到发布的值,始终为null。
解决方法:
以下是一个示例代码,演示了如何在ASP.NET Core Web API中接收和处理JSON数据:
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
[HttpPost]
public IActionResult CreateUser([FromBody] User user)
{
// 处理接收到的User对象
// ...
return Ok();
}
}
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
以上代码中,UserController类包含了一个HttpPost方法,该方法接收一个User对象作为参数,并处理该对象。注意该方法的参数上使用了[FromBody]属性,以指定从请求体中绑定参数。
确保请求的Body包含正确的JSON数据,并且Content-Type设置为application/json。请求示例:
POST /api/user
Content-Type: application/json
{
"name": "John",
"age": 30
}
通过以上步骤,应该能够解决ASP.NET Core Web API无法接收到发布的值始终为null的问题。