ASP.NET Core Web API Posts All Enums as 0th Option

Viewed 270

I have started building a webapi. I have a model class like so:

public class ParentItem
    {
        public long Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public string Profession { get; set; }
        public string PhoneNumber { get; set; }
        public CaretakerType Caretaker { get; set; }
        public string Email { get; set; }
        
    }

    public enum CaretakerType 
    {
        Father,
        Mother,
        LegalGuardian,
        EmergencyContact
    }

The post method at the moment is just the default

        [HttpPost]
        public async Task<ActionResult<ParentItem>> PostParentItem(ParentItem parentItem)
        {
            _context.ParentItems.Add(parentItem);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetParentItem), new { id = parentItem.Id }, parentItem);
        }

However, whenever I test the post method with postman, like so:

{
    "firstName": "Person",
    "lastName" : "Name",
    "address" : "an address",
    "profession": "a profession",
    "phoneNumber": "a number",
    "caretakerType": "Mother",
    "email": "an email"
}

With Raw radio button and as type JSON, it always returns

{
    "id": 1,
    "firstName": "Person",
    "lastName": "Name",
    "address": "an address",
    "profession": "a profession",
    "phoneNumber": "a number",
    "caretaker": "Father",
    "email": "an email"
}

It doesn't matter if I say Mother, LegalGuardian, or EmergencyContact it always comes back as "Father." Why is this? Target Framework is net5.0. I am using EntityFrameworkCore.SqlServer and EntityFrameworkCore.InMemory at the moment.

1 Answers

Your JSON has a different name to your DTO class's property name.

public class ParentItem
    {
        public long Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public string Profession { get; set; }
        public string PhoneNumber { get; set; }
        public CaretakerType Caretaker { get; set; }  // <---- "Caretaker"
        public string Email { get; set; }
        
    }
{
    "firstName": "Person",
    "lastName" : "Name",
    "address" : "an address",
    "profession": "a profession",
    "phoneNumber": "a number",
    "caretakerType": "Mother",            // <-- "caretakerType"
    "email": "an email"
}

Change your JSON to this:

{
    "firstName": "Person",
    "lastName" : "Name",
    "address" : "an address",
    "profession": "a profession",
    "phoneNumber": "a number",
    "caretaker": "Mother",            // <-- "caretaker"
    "email": "an email"
}
Related