Search code examples
asp.net-coreasp.net-core-webapi

ASP.NET Core Web API: POST Complex Json data, child object always null


My project: ASP.NET Core 8 Web API, I am using VS 2022.

These are my model classes:

public class Person 
{
    public Guid ID { get; set; }
    public string Name { get; set; }
    public string Age { get; set; }
    public Address? Address { get; set; }
}

public class Address
{
    public Guid ID { get; set; }
    public string? Street { get; set; }
    public int number { get; set; } = 0;
    public string? City { get; set; }
}

This is my controller:

[HttpPost("register")]
[Consumes("application/json")]
[ApiVersion("1.0")]
public async Task<IActionResult> Register([FromBody] Person person)
{
    if (person == null) 
    {
        return BadRequest();
    }

    return Ok();
}

This is my Json (Post request):

{
    "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "name": "Peter Lee",
    "age": 10,
    "address.id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "address.street": "Mano Hoo Street"
}

The problems are:

  1. Person address parameter always null, for others it works fine.
  2. When the code is debugged, and the post data is null, the debug break point is never entered.

I'm using Postman to send POST messages in "application/json" for content type.

Can someone tell me what I'm doing wrong?


Solution

  • The correct json formate should like below:

    {
      "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      "name": "Peter Lee",
      "age": 10,
      "address": {
        "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
        "street": "Mano Hoo Street",
        "number": 0,
        "city": "string"
      }
    }