[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/nvl1G.png
[Route("api/values")]
[ApiController]
public class ValuesController : ControllerBase
{
[Route("asd")]
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
[Route("Test")]
[HttpPost]
public IActionResult Test([FromBody] Person p)
{
return Ok(p);
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
IM使用ASP.NET核心用于Web API。目前正在进行测试。正在使用Postman将JSON对象发布到Web API。但是我无法获得对象。以下是Web API返回的消息
{
"errors": {
"": [
"A non-empty request body is required."
]
} ,
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "80000099-0007-fd00-b63f-84710c7967bb"
}
请分享您在Postman中提供的有效载荷。请确保您将有效载荷添加为主体部分中的对象,并将内容类型设置为JSON(application/json(。
有效载荷应与对象的有效载荷匹配。在您的情况下,可能是:
{
"FirstName": "my First Name",
"LastName" : "my last Name",
"Age": 28
}
另外,在您的情况下,在ASP.NET Core中不需要[从Body]进行复杂类型的序列化。
https://learn.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-2.2
[来自Body]的复杂类型参数是推断的。一个例外 [来自Body]推理规则是任何复杂的内置类型, 特殊含义,例如iformcollection和natcellationToken。这 绑定源推理代码忽略了这些特殊类型。
[来自Body]的简单类型,例如字符串或INT。 因此,[来自Body]属性应用于简单类型 当需要该功能时。