ASP.NET Core can't get object from body

Viewed 3875

Code:

[HttpPost("user/register")]
public IActionResult Register([FromBody] User user)
{
    if (user?.Name is null || user?.Password is null)
    {
        return BadRequest(new {message = "User is null and/or name and password are not provided"});
    }
    else
    {
         // Add to db
         return Json(user);
    }
}

Also the User class:

public class User
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Password { get; set; }
    public string Role { get; set; }
}


It should basically get a user and add it to the database. I tried sending this json:

{ "Name": "Batman", "Password": "IronmanSucks"}

The app caught the request, but the user object was null. I also tried with:

{ "user": { "Name": "Batman", "Password": "IronmanSucks"} }

But according to this documentation, the first json should have worked fine.

Here is a link to an example http request in postman


Does this have to do with the headers or is it a bug in .NET Core 2.0?

3 Answers

I believe that the Model is coming up as invalid hence why it is null. You should try adding a [BindNever] attribute into the User class for the Role and Guid properties, seeing as you aren't using them.

If that doesn't work you may try using extended classes like so:

public class User
{
    public string Name { get; set; }
    public string Password { get; set; }
}

public class DataUser : User
{
    public Guid Id { get; set }
    public string Role { get; set; }
}
Related