从自定义验证器中的验证上下文的基本类型获取值

Pet*_*ete 1 c# validation c#-4.0 asp.net-mvc-4

我正在尝试编写自己的验证属性,但是我无法从继承的类中获取属性的值.这是我的代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

我不知道我的意思是什么,GetValue因为它期待一个对象,但我传递的所有内容都给我一个属性类型与目标异常不匹配

我不得不转到基类型,因为我试图从继承的类中获取属性的值,并且context.ObjectInstance不包含必要的属性

dee*_*see 7

您可以简单地将对象转换为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;
}
Run Code Online (Sandbox Code Playgroud)

context.ObjectInstanceobject类型而不是模型的类型,因为验证框架不是为了显式验证模型而创建的,而是正确的对象实例.一旦它被铸造,你可以正常使用它.

作为旁注,您遇到错误的原因property.GetValue(context.ObjectType.BaseType)是因为该GetValue方法需要您正在调用其属性的对象的实例.