有时,我们可能会希望在验证规则运行时返回相验证时的上下文信息。 使用WithState该方法允许我们返回任何自定义的数据
例如
public class PersonValidator : AbstractValidator<Person>\
{
public PersonValidator()
{
RuleFor(person => person.Surname).NotNull();
RuleFor(person => person.Forename).NotNull().WithState(person => 1234);
}
}
然后 我们通过 ValidationFailure.CustomState 来获取这个值
var validator = new PersonValidator();
var result = validator.Validate(new Person());
foreach (var failure in result.Errors)
{
Console.WriteLine($"Property: {failure.PropertyName} State: {failure.CustomState}");
}
输出为:
Property: Surname State:
Property: Forename State: 1234