ASP.NET Core 2.1 中出现第一个错误后如何停止验证

How to stop validation after first error in ASP.NET Core 2.1

我知道这个问题在其他框架和语言中被问过好几次,但我想知道一旦它在 ASP.NET Core 2.1 中出现第一个错误,我如何才能真正停止我的模型验证?

    [Required(ErrorMessage = Email.requiredErrorMessage)]
    [DataType(DataType.EmailAddress, ErrorMessage = Email.formatErrorMessage)]
    [StringLength(Email.maximumLength, MinimumLength = Email.minimumLength, ErrorMessage = Email.rangeErrorMessage)]
    [EmailExists(ErrorMessage = Email.doesNotExistsMessage)]
    public string email { get; set; }

    [Required(ErrorMessage = ConfirmationCode.requiredErrorMessage)]
    [RegularExpression(ConfirmationCode.regularExpression, ErrorMessage = ConfirmationCode.formatErrorMessage)]
    public string confirmationCode { get; set; }

以上代码是 API 模型验证,在发出补丁请求后,我收到以下响应:

"email":[
"This email does not exist in database"
],
"confirmationCode":[
"Confirmation code format is invalid"
]
}

我不希望模型验证在确保数据库中不存在电子邮件时继续进行,只是 return 那个错误并且不再继续验证。

您可以配置在注册 MVC 服务时 MVC 将处理的最大错误数:

services.AddMvc(options => options.MaxModelValidationErrors = 1);

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.1#model-state

MVC will continue validating fields until reaches the maximum number of errors (200 by default). You can configure this number by inserting the following code into the ConfigureServices method in the Startup.cs file:

也就是说,您不一定能控制这些错误的处理顺序。要处理这个问题,您可能需要添加一些自定义验证逻辑,这也在上面讨论过 link .