c# - ASP.NET 5、MVC 6、Web API -> ModelState.IsValid 始终返回 true

标签 c# asp.net asp.net-web-api asp.net-core

我看过很多关于 IsValid 始终为真的帖子,但没有一个能帮助我解决这个问题。我也在使用 MVC5 的 ASP.NET 4 中看到了这个问题。很明显,我在某处错过了一步。

Controller 方法:

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

值对象类:

public class ValuesObject
{
    [Required]
    public string Name;

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

帖子正文:

{
  Age: 1
}

ModelState.IsValid 为真。

但我预计 Required 和 Range 验证都会失败。

我错过了什么??

谢谢,

凯文

最佳答案

您不能在模型中使用字段。这是one of general conditions供您验证。

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

用属性替换它,一切都会正常工作:

public class ValuesObject
{
    [Required]
    public string Name { get; set; }

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

关于c# - ASP.NET 5、MVC 6、Web API -> ModelState.IsValid 始终返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34584294/

相关文章:

asp.net-web-api - .Net Web API IActionFilter.OnActionExecuted 返回类型

asp.net - 如何在其他 Controller 中使用授权用户名

c# - 使用 AngularJs 从数据库中检索和过滤数据

c# - 为什么此行在 .NET 4 下运行时会导致 VerificationException?

java - AES 加密 JAVA 和 ASP .Net

c# - WebClient上传文件错误

c# - MVC : model of type Nullable<T>

c# - Fluent NHibernate 异常在集合之间移动对象

c# - 从 SqlCommand 对象发送什么 SQL

wcf - 微软WCF数据服务技术的 future 是什么?应该开始迁移到 WebAPI 吗?