在验证自定义属性时获取其他属性属性

时间:2015-04-27 09:58:56

标签: .net validation reflection data-annotations custom-attributes

我创建了一个验证属性。 IsValid方法如下

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
public sealed class BlaBlaAttribute : ValidationAttribute
{

    private readonly object _typeId = new object();
    //...........

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {

        var otherProperties = validationContext.ObjectType.GetProperties(BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance).ToList();

        foreach (void propItem in otherProperties) {  
            // propItem.CustomAttributes.Count is zero for each and every property              
            DisplayAttribute attr = (DisplayAttribute)Attribute.GetCustomAttribute(propItem, typeof(DisplayAttribute));
            if (attr == null) {
                //............
            }
        }
        return ValidationResult.Success;
    }
}

该属性使用如下

[MetadataType(typeof(SiteContact.SiteContactMD))]
public class SiteContact
{
    public class SiteContactMD
    {
        [BlaBla()]
        [Display(Name = "First Name")]
        public override string christian { get; set; }
        [Display(Name = "Last Name")]
        public virtual string surname { get; set; }

        [BlaBla()]
        [Display(Name = "Email Id")]
        public override string EMail { get; set; }
    }
}

有一些显示属性,但attr始终为空。如何获得其他属性自定义属性?

2 个答案:

答案 0 :(得分:0)

您已使用类DisplayAttribute的实例修饰了属性。

[Display(Name = "First Name")]
public override string christian { get; set; }

但是,您尝试获取DisplayNameAttribute类型的属性:

GetCustomAttribute(propItem, typeof(DisplayNameAttribute))

答案 1 :(得分:0)

找到this thread后,我找到了获取显示属性的方法。

 protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {

        var otherProperties = validationContext.ObjectType.GetProperties(BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance).ToList();

        //To get the assigned MetaDataAttribute for the class
        var metaData = validationContext.ObjectType.GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType<MetadataTypeAttribute>().ToArray().FirstOrDefault(); 

        foreach (void propItem in otherProperties) {  

            if (metaData != null) 
            {
                 // Get display attributes for the property
                 var attrs = metaData.MetadataClassType.GetProperty(propItem ).GetCustomAttributes(typeof(DisplayAttribute), true).OfType<DisplayAttribute>.ToArray();
                 if (attrs.Count > 0) 
                 {
                    this.OtherPropertyDisplayName = ((DisplayAttribute)attrs.FirstOrDefault()).Name;
                     //.............
                 }
            }
        }
        return ValidationResult.Success;
    }

希望,这可能有助于某人。