Reputation: 49
[![enter image description here][1]][1]
[1]: https://i.sstatic.net/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 using asp.net core for web api. Currently doing testing on. Was using postman to post json object to web api. But i am not able to get the object. Below is the message return from 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"
}
Upvotes: 1
Views: 2632
Reputation: 2574
Please share the payload that you are providing in Postman. Please make sure that you are adding the payload as an object in the body section and set the content type as JSON(application/json).
The payload should match as that of your object. In your case it can be:
{
"FirstName": "my First Name",
"LastName" : "my last Name",
"Age": 28
}
Also, In your case [FromBody] is not required in Asp.Net Core as it serializes by default for Complex types.
https://learn.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-2.2
[FromBody] is inferred for complex type parameters. An exception to the [FromBody] inference rule is any complex, built-in type with a special meaning, such as IFormCollection and CancellationToken. The binding source inference code ignores those special types.
[FromBody] isn't inferred for simple types such as string or int. Therefore, the [FromBody] attribute should be used for simple types when that functionality is needed.
Upvotes: 1