当我检查我的ModelState [" Email"]。错误我发现相同的验证错误重复了3次,而且对于我的所有模型都是3次,我的模型包含3个以上的属性。
我想知道为什么这些规则会被执行三次。 我正在使用MVC 5,使用Autofac。我找不到错误! 没有错误,但是如果每个属性被验证3次,一些验证很复杂,有时连接到数据库,我会担心性能。 下面是我用来注册Validators,Fluent Validation和Autofac的代码。
builder.RegisterAssemblyTypes(System.Reflection.Assembly.Load("MyAssembly"))
.Where(t => t.Name.EndsWith("Validator"))
.AsImplementedInterfaces()
.InstancePerRequest();
builder.RegisterType<FluentValidationModelValidatorProvider>().As<ModelValidatorProvider>();
builder.RegisterType<AutofacValidatorFactory>().As<IValidatorFactory>().SingleInstance();
Container = builder.Build();// Build !
// FluentValidation wire up to MVC
var fluentValidationModelValidatorProvider = new FluentValidationModelValidatorProvider()
{
AddImplicitRequiredValidator = false,
ValidatorFactory = new AutofacValidatorFactory()
};
//fluentValidationModelValidatorProvider.AddImplicitRequiredValidator = false;
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
ModelValidatorProviders.Providers.Add(fluentValidationModelValidatorProvider);
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(Container);
模型看起来像:
public class ContactInfoDTO
{
public int ID { get; set; }
public string Email { get; set; }
public string Email2 { get; set; }
public string PhoneNumber { get; set; }
public string PhoneNumber2 { get; set; }
public string EmergencyNumber { get; set; }
public string EmergencyPersonName { get; set; }
public ContactInfoDTO()
{
}
}
答案 0 :(得分:0)
这是你应该如何使用Fluent验证:
using FluentValidation;
public class CustomerValidator: AbstractValidator<Customer> {
public CustomerValidator() {
RuleFor(customer => customer.Surname).NotEmpty();
RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name");
RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);
RuleFor(customer => customer.Address).Length(20, 250);
RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
}
private bool BeAValidPostcode(string postcode) {
// custom postcode validating logic goes here
}
}
Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer);
bool validationSucceeded = results.IsValid;
IList<ValidationFailure> failures = results.Errors;
您应该为您的模型创建一个验证器,以便您可以控制验证对象时发生的情况。
答案 1 :(得分:0)
感谢大家,感谢他们的支持。 感谢FluentValidation的所有者Jeremy Skinner先生对此进行了调查,这是下面解决方案的链接。 毕竟这是我的错:)
https://github.com/JeremySkinner/FluentValidation/issues/362