gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:02:35 25 4
gpt4 key购买 nike

我看过很多关于 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com