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

Controller doesn't read request body


I have two controllers for Account and Pet. Both have a method marked with the [HttpPost] annotation; their objects are passed to the method.

public class AccountController : Controller
{
    private Accounts _accounts;

    public AccountController(Accounts accounts) 
    {
        _accounts = accounts;
    }

    [HttpPost]
    public async Task<IActionResult> Registration([FromBody]Account account)
    {
        List<Claim> claims = new()
        {
            new Claim(ClaimTypes.Name, account.Login),
        };

        await HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies")));

        if (_accounts.AddAccount(account))
            return Ok("You registered!");
        else 
            return BadRequest("Unable to register user!");
    }
}

[Authorize]
public class PetController : Controller
{
    private Pets _pets;

    public PetController(Pets pets) 
    {
        _pets = pets;
    }

    [HttpPost]
    public IActionResult Add([FromBody]PetShipping petShipping)
    {
        var user = HttpContext.User.FindFirst(ClaimTypes.Name)?.Value;

        if (user == null)
        {
            return BadRequest("Username not found! It is impossible to create an animal.");
        }

        _pets.AddPet(user, petShipping.TypePet, petShipping.Name);

        return Ok("You purchased an animal");
    }
}

My models classes:

public class PetShipping
{
    public string Name { get; set; } = string.Empty;
    public PetType TypePet { get; set; } = PetType.None;
}

public class Account
{
    public string Login { get; set; } = string.Empty;
    public string Password { get; set; } = string.Empty;
}

In the AccountController Registration() method, when I pass the model in the form of JSON in Postman, it processes and everything goes well, but when I do the same with PetController.Add(), it sees the object as null. I don't see what is my mistake.

Can you guide me and give me some advice?

Postman screenshots, Content-Type = application/json:

enter image description here

enter image description here

I looked for this error on the Internet, but all it says is to set the [FromBody] attribute, check the content-type as application/json and check the sent JSON.


Solution

  • I think it's because of the Enum (PetType) which you used in Pet Shipping, in postman you have to pass the assigned value of each enum members. for example use this json:

    {"Name" : "Test","PetType" : 1}