基本上,我创建了一个扩展 ObjectValidator 的自定义验证器,并添加了一个 _PropertyName 字段,该字段被预先添加到验证结果的键中。
所以现在上面描述的例子中的用法是:
public class Profile
{
...
[SuiteObjectValidator("HomeAddress")]
public Address HomeAddress { get; set; }
[SuiteObjectValidator("WorkAddress")]
public Address WorkAddress { get; set; }
}
验证器类:
public class SuiteObjectValidator : ObjectValidator
{
private readonly string _PropertyName;
public SuiteObjectValidator(string propertyName, Type targetType)
: base(targetType)
{
_PropertyName = propertyName;
}
protected override void DoValidate(object objectToValidate, object currentTarget, string key,
ValidationResults validationResults)
{
var results = new ValidationResults();
base.DoValidate(objectToValidate, currentTarget, key, results);
foreach (ValidationResult validationResult in results)
{
LogValidationResult(validationResults, validationResult.Message, validationResult.Target,
_PropertyName + "." + validationResult.Key);
}
}
}
以及必要的属性类:
public class SuiteObjectValidatorAttribute : ValidatorAttribute
{
public SuiteObjectValidatorAttribute()
{
}
public SuiteObjectValidatorAttribute(string propertyName)
{
PropertyName = propertyName;
}
public string PropertyName { get; set; }
protected override Validator DoCreateValidator(Type targetType)
{
var validator = new SuiteObjectValidator(PropertyName, targetType);
return validator;
}
}