gpt4 book ai didi

.net - ModelState.IsValid 在使用数据注释时始终为真,MVC 作为 Web API

转载 作者:行者123 更新时间:2023-12-03 18:18:59 24 4
gpt4 key购买 nike

我见过很多这样的问题,但没有答案能解决我的问题。我可以提交一个包含空格的名称,或者将描述字段留空,而 ModelState 仍然有效。

在我的 StartUp.cs 中我确实使用了

services.AddMvc();

我确实在没有 Validator.TryValidateObject 的情况下进行了尝试,并且 Model.State 始终有效。

我的类(class)有数据标注

public class UpdateAttributeResource
{
[Required, MaxLength(96), RegularExpression(@"^[A-Za-z0-9~_$\-]*$")]
public string Name;
[Required, MaxLength(96)]
public string DisplayName;
[Required, MaxLength(160)]
public string DescriptionEn;
[Required, MaxLength(160)]
public string DescriptionFr;
public string Comments;
}

我的 Controller 接收到我的类的集合,即使在使用 TryValidateObject 强制验证时,ModelState 仍然有效

public IActionResult UpdateAttributes([FromBody]UpdateAttributeResource[] updateAttributes)
{
var validationContext = new ValidationContext(updateAttributes[0], null, null);
var validationResults = new List<ValidationResult>();

var isValid = Validator.TryValidateObject(updateAttributes[0], validationContext, validationResults, true);

if (!isValid)
{
ModelState.AddModelError("NOPE", "Nope");
return BadRequest(ModelState);
}

最佳答案

其实我终于在这里找到了答案 DataAnnotations tryvalidateobject always returns true

不知道为什么之前没有弹出,反正

The validator ignores the [RequiredAttribute] on fields - it takes into an account only properties;

所以我只需要将我的类(class)更改为

public class UpdateAttributeResource
{
[Required, MaxLength(96), RegularExpression(@"^[A-Za-z0-9~_$\-]*$")]
public string Name { get; set; }
[Required, MaxLength(96)]
public string DisplayName { get; set; }
[Required, MaxLength(160)]
public string DescriptionEn { get; set; }
[Required, MaxLength(160)]
public string DescriptionFr { get; set; }
public string Comments;
}

关于.net - ModelState.IsValid 在使用数据注释时始终为真,MVC 作为 Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49659219/

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