I’m trying to query attributes and access the base type of several attributes. For some reason it is failing to cast properly and not executing as expected. Here is the code below:
internal static void ValidateProperties(TModel model, ModelStateDictionary modelState)
{
Type type = model.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
foreach(Attribute attribute in property.GetCustomAttributes(true))
{
ValidationAttribute validationAttribute = attribute as ValidationAttribute;
if (validationAttribute != null)
{
if (!validationAttribute.IsValid(property.GetValue(model, null)))
modelState.AddModelError(property.Name, validationAttribute.ErrorMessage);
}
}
}
}
For some reason validateAttribute is always null. In debugging it won’t cast CustomValidationAttribute or RequiredAttribute. Trying to directly cast to ValidationAttribute instead of using the “as” keyword results in an Invalid Cast exception for both of these types as well. Clearly they are derived from ValidationAttribute: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute.aspx
What am I missing? Thanks!
Edit: Per request, I’ve added an Debug statement to output the Type of the Attribute. The results are as follows:
System.ComponentModel.DataAnnotations.CustomValidationAttribute
System.ComponentModel.DataAnnotations.RequiredAttribute
System.ComponentModel.DataAnnotations.RegularExpressionAttribute
System.ComponentModel.DataAnnotations.CustomValidationAttribute
System.ComponentModel.DataAnnotations.RequiredAttribute
It doesn’t look like you’re missing anything or doing anything wrong, so here’s a shot in the dark: are the assemblies (the one querying and the one being queried) using different (strong-named) versions of the System.ComponentModel.DataAnnotations.dll?