Deivyyyy
Deivyyyy

Reputation: 27

Controller does not recognize passed properties

I'm creating a web api with ASP.NET Core and I've encountered a problem. I have a post request and I want to pass a Municipality object to it with JSON format. The problem is that I have property Name with attribute [Required]. I call the endpoint by using Postman with this JSON payload {"Name": "London"} and when validating the model, it says "The Name field is required." even though it was definitely provided.

I've tried using [FromBody] attribute, but the problem with it is that it doesn't give me validation errors and only says, that "input was invalid" and gives a null object, so not using this attribute gives a lot better errors.

Github: https://github.com/DeividasBrazenas/Taxes/blob/master/Taxes/Taxes/Controllers/BaseController.cs

BaseModel.cs

public class BaseModel
{
    public int Id { get; set; }
}

Municipality.cs

public class Municipality : BaseModel
{
    [Required]
    public string Name { get; set; }
    public ICollection<Tax> Taxes { get; set; }
}

MunicipalitiesController.cs

    [EnableQuery]
    public async Task<IActionResult> Post(Municipality baseObject)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        await Context.Set<Municipality>().AddAsync(baseObject);
        await Context.SaveChangesAsync();
        return Created(baseObject);
    }

Screenshot of POST request - enter image description here

Upvotes: 1

Views: 510

Answers (1)

Edward
Edward

Reputation: 29976

Make changes below for your current MunicipalitiesController

  1. Add public async Task<IActionResult> Post(Municipality baseObject) with FromBody

    [EnableQuery]
    [HttpPost]
    public async Task<IActionResult> Post([FromBody]Municipality baseObject)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
    
        await Context.Set<Municipality>().AddAsync(baseObject);
        await Context.SaveChangesAsync();
        return Created(baseObject);
    }
    
  2. Change the json request to lowercase.

    {
            "name":"1231"
    }
    

Upvotes: 1

Related Questions