ASP.NET 5, MVC6, WebAPI -> ModelState.IsValid alwa

2019-06-17 05:35发布

I've seen a lot of posts about IsValid always being true but none of them have helped me solve this problem. I'm also seeing this problem in ASP.NET 4 using MVC5. So clearly 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 of the POST:

{
  Age: 1
}

ModelState.IsValid is true.

But I would expect both the Required and Range validations to fail.

What am I missing??

Thanks,

Kevin

1条回答
等我变得足够好
2楼-- · 2019-06-17 06:28

You can't use fields in your model. it's one of general conditions for your validation.

In ASP.NET Web API, you can use attributes from the System.ComponentModel.DataAnnotations namespace to set validation rules for properties on your model.

Replace it with properties and all 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; }
}
查看更多
登录 后发表回答