mike
mike

Reputation: 143

Asp.Net core WebApi modelstate not working

I have this webapi and trying to use the "modelstate.IsValid" function, but i have ran into some strange problem. I have the following method in my controller:

[HttpPut]
    [Route("{id}")]
    public async Task<IActionResult> Put([FromBody]ItemUpdateModel model, [FromRoute]int id)
    {
        if (!ModelState.IsValid) //Here i have a breakpoint!
        {
            return BadRequest(new
            {
                code = 400,
                message = ModelState.Values.First().Errors.First().ErrorMessage
            });
        }
}

And here is the model, ItemUpdateModel

using System.ComponentModel.DataAnnotations;

namespace TestApi.Models
{
    public class ItemUpdateModel
    {
        [Required]
        [Display(Name = "title")]
        [MaxLength(40)]
        public string Title { get; set; }

        [Required]
        [Display(Name = "discount")]
        public double Discount { get; set; }

        [Required]
        [Display(Name = "priceupdate")]
        public bool PriceUpdate { get; set; }
    }
}

I use Postman to send this http-request in the body with verb PUT and format json:

{ "title": "Some test", "discount": 0, "priceupdate": false }

This request should pass ok, but even if i try to leave out some properties the modelstate is always true. So when looking into the modelstate, this model aint binding at all to it. Only the [FromRoute]int id is bind, and the modelstate gets valid.

The model is anyway getting filled with data and working except from the modelstate validation/binding.

Also in the header im including: "application/json; charset=utf-8"

Anyone can help me with this, i have struggled a lot with this that seems like a really simple task :)

Thanks!

Upvotes: 4

Views: 4399

Answers (2)

Bart Calixto
Bart Calixto

Reputation: 19725

You need to also use [BindRequired] if you want the properties to be required/exists on the payload.

Upvotes: 0

mike
mike

Reputation: 143

Solved this, finally.

For some reason the modelstate aint dealing with the model if its "valid". And the model is getting valid by the JSON formatter adding the missing values for the datatypes double and int by adding value 0 or false for booleans. The solution was to make the properties nullable in the model, like

public double? Price { get; set; }

Now when i post the request, the price is NULL and presented in the modelstate as invalid.

Upvotes: 2

Related Questions