ASP.NET 5,MVC6,的WebAPI - > ModelState.IsValid总是返回true [英] ASP.NET 5, MVC6, WebAPI -> ModelState.IsValid always returns true

查看:1067
本文介绍了ASP.NET 5,MVC6,的WebAPI - > ModelState.IsValid总是返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了很多的IsValid始终是真实的职位,但他们都没有帮我解决这个问题。我现在在ASP.NET 4使用MVC5看到了这个问题。所以显然我错过了一步的地方。

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.

控制器方法:

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

Values​​Object类:

ValuesObject Class:

public class ValuesObject
{
    [Required]
    public string Name;

    [Range(10, 100, ErrorMessage = "This isn't right")]
    public int Age;
}

在POST的正文:

Body of the POST:

{
  Age: 1
}

ModelState.IsValid是真实的。

ModelState.IsValid is true.

但我希望Required和范围都验证失败。

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

我缺少什么?

谢谢,

凯文

推荐答案

您不能使用模型中的各个领域。这是<一个href=\"http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api\">one一般情况了解您的验证。

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

在ASP.NET的Web API,你可以使用从属性
  System.ComponentModel.DataAnnotations命名空间设置验证
  规则的属性在您的模型。

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; }
}

这篇关于ASP.NET 5,MVC6,的WebAPI - &GT; ModelState.IsValid总是返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆