我正在尝试编写自己的验证属性,但我无法从继承的类中获取属性的值。这是我的代码:
protected override ValidationResult IsValid(object value, ValidationContext context)
{
if (context.ObjectType.BaseType == typeof(AddressModel))
{
PropertyInfo property = context.ObjectType.BaseType.GetProperty(_propertyName);
// this is the line i'm having trouble with:
bool isRequired = (bool)property.GetValue(context.ObjectType.BaseType);
return base.IsValid(value, context);
}
return ValidationResult.Success;
}
我不知道我要传递给
GetValue
的内容是什么?因为它期待一个对象,但我传入的所有内容都给了我一个 属性类型与目标不匹配 异常(exception)当我试图从继承的类和
context.ObjectInstance
中获取属性的值时,我不得不转到基本类型。不包括必要的属性
最佳答案
您可以简单地将您的对象转换为 AddressModel
并像那样使用它。
protected override ValidationResult IsValid(object value, ValidationContext context)
{
var addressModel = context.ObjectInstance as AddressModel
if (addressModel != null)
{
// Access addressModel.PROPERTY here
return base.IsValid(value, context);
}
return ValidationResult.Success;
}
context.ObjectInstance
属于 object
type 而不是模型的类型,因为验证框架不是为了显式验证模型而创建的,但它是正确的对象实例。投出后就可以正常使用了。作为旁注,您收到
property.GetValue(context.ObjectType.BaseType)
错误的原因是因为 GetValue
方法需要您正在调用其属性的对象的实例。
关于c# - 从自定义验证器中验证上下文的基本类型获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21629167/