gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:27 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com