.Net Core Model Binding JSON Post To Web API
NOTE: If you are using aspnet core 3.0, the solution can be found here. For other versions, keep reading.
You need to mark your parameter as coming from the body with the FromBody
attribute like this:
[HttpPost]
[Route("test1")]
[AllowAnonymous]
public IActionResult Test([FromBody] Class1 data)
{
return Ok();
}
You need to make sure you're using application/json
as your content type from Postman:
Resulting in:
Make sure your property setters are public as well:
public class Person
{
public String Name;
public Int32 Age;
}
I was struggling with this too, and thought I would share one item that was necessary for me and not in the accepted answer, I needed to add {get; set;} to each attribute in my class as so:
public class LogString{
public string val {get; set;}
public string data {get; set;}
}
The rest was the same:
[HttpPost]
public void Post([FromBody] LogString message)
{
Console.WriteLine(message.val);
}
After adding that it started working.