c# - Fluent Validation 验证器在添加验证代码之前就会导致错误

标签 c# fluentvalidation

我正在使用 Contoso 大学项目尝试 Fluent Validation。

因此,我向现有类添加了验证器属性:

[Validator(typeof(PersonValidator))]
public abstract class Person
{
    public int ID { get; set; }

    [Required]
    [StringLength(50)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }
}

我的 PersonValidator 尚未执行任何操作:

public class PersonValidator : AbstractValidator<Person>
{
    public PersonValidator()
    {
    }
}

但是当我访问学生的创建页面时,我的调试器停止在 EditorFor 行上......

 @Html.EditorFor(model => model.LastName, 
      new { htmlAttributes = new { @class = "form-control" } })

….我收到一个错误:

Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: required

我似乎没有多次对同一元素进行相同的验证,那么为什么我会收到错误? Fluent Validation 可以与 MVC 的内置验证一起使用吗?

最佳答案

如果您将 FluentValidation 与 DataAnnotations 一起使用,则可能会发生这种情况。尝试在 Application_Start 中执行类似的操作

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
FluentValidationModelValidatorProvider.Configure(provider => provider.AddImplicitRequiredValidator = false);
var fluentValidationModelValidatorProvider = new FluentValidationModelValidatorProvider(new AttributedValidatorFactory());
ModelValidatorProviders.Providers.Add(fluentValidationModelValidatorProvider);

关于c# - Fluent Validation 验证器在添加验证代码之前就会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52670005/

相关文章:

c# - 在类库中访问 session 。

c# - 空对象的 FluentValidation 规则

c# - ServiceStack - 消息队列服务(验证和过滤)

c# - 检查属性在 FluentValidation 列表中是否唯一

c# - 自定义 ServiceStack 验证响应

c# - 如何将文本框/组合框值传递给 rdlc 报告文本字段?

c# - 这是一种安全且*相对可行*的异步记录某些事件的方法吗?

c# - 我如何将 ActionLink "Add Pictures"放在导航栏的中间?

c# - 如何跟踪循环中完成了多少异步任务?