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!