ValidationContext是.NET中System.ComponentModel.DataAnnotations命名空间下的一个类,它提供了验证操作执行的上下文信息。它是数据注解验证系统的重要组成部分,用于在执行验证时提供额外的上下文信息。
ValidationContext主要有以下功能:
ObjectInstance
: 获取要验证的对象ObjectType
: 获取要验证的对象的类型MemberName
: 获取或设置要验证的成员名称DisplayName
: 获取或设置要验证的成员的显示名称Items
: 获取与此上下文关联的键/值对字典GetService(Type)
: 获取指定类型的服务InitializeServiceProvider(Func<Type, object>)
: 初始化服务提供程序public class CustomValidationAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// 使用validationContext获取服务或其他上下文信息
var service = (IMyService)validationContext.GetService(typeof(IMyService));
// 验证逻辑...
if (/* 验证失败 */)
{
return new ValidationResult("错误消息", new[] { validationContext.MemberName });
}
return ValidationResult.Success;
}
}
var model = new MyModel();
var context = new ValidationContext(model);
var results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(model, context, results, true);
var propertyValue = model.PropertyToValidate;
var context = new ValidationContext(model) { MemberName = nameof(model.PropertyToValidate) };
var results = new List<ValidationResult>();
bool isValid = Validator.TryValidateProperty(propertyValue, context, results);
原因: ValidationContext默认没有配置服务提供程序 解决:
var serviceProvider = new ServiceCollection()
.AddSingleton<IMyService, MyService>()
.BuildServiceProvider();
var context = new ValidationContext(model, serviceProvider, null);
原因: 没有正确设置MemberName或使用错误的属性名 解决:
var context = new ValidationContext(model)
{
MemberName = nameof(model.PropertyName)
};
原因: TryValidateObject默认不验证必需(Required)属性 解决:
Validator.TryValidateObject(model, context, results, validateAllProperties: true);
public class DateRangeAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext context)
{
var model = (MyModel)context.ObjectInstance;
if (model.StartDate >= model.EndDate)
{
return new ValidationResult("结束日期必须大于开始日期",
new[] { nameof(model.StartDate), nameof(model.EndDate) });
}
return ValidationResult.Success;
}
}
var context = new ValidationContext(model)
{
Items = { ["AdditionalData"] = "SomeValue" }
};
ValidationContext是.NET数据注解验证系统的核心组件,它提供了丰富的上下文信息,使得验证逻辑可以更加灵活和强大。通过合理使用ValidationContext,可以实现复杂的验证场景,同时保持代码的整洁和可维护性。