ASP.NET 5, MVC6, WebAPI & # 8594; ModelState.IsValid always returns true

I have seen many reports about IsValid that are always true, but none of them have helped me solve this problem. I also see this problem in ASP.NET 4 using MVC5. It’s so clear that I’m missing a step somewhere.

Controller Method:

public IHttpActionResult Post([FromBody]ValuesObject value) { if (ModelState.IsValid) { return Json(value); } else { return Json(ModelState); } } 

ValuesObject Class:

 public class ValuesObject { [Required] public string Name; [Range(10, 100, ErrorMessage = "This isn't right")] public int Age; } 

Body POST:

 { Age: 1 } 

ModelState.IsValid - true.

But I would expect both Required and Range checks to fail.

What am I missing?

Thanks,

Kevin

+7
c # asp.net-web-api asp.net-core
source share
1 answer

You cannot use fields in your model. This is one of the general conditions for your verification.

In the ASP.NET Web API, you can use the attributes from the System.ComponentModel.DataAnnotations namespace to set the rule check for properties in your model.

Replace it with properties, and everything will work fine:

 public class ValuesObject { [Required] public string Name { get; set; } [Range(10, 100, ErrorMessage = "This isn't right")] public int Age { get; set; } } 
+13
source share

All Articles