How can I find Data Annotation attributes and their parameters using reflection

I have a data annotation attribute, for example:

[StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")] 

How can I find data annotation attributes and their parameters using reflection?

thanks

+8
reflection c # attributes data-annotations
source share
1 answer

I assume you have something like this:

 [StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")] public string FirstName {get;set;} 

To get the attribute and property from it:

 StringLengthAttribute strLenAttr = typeof(Person).GetProperty("FirstName").GetCustomAttributes( typeof(StringLengthAttribute), false).Cast<StringLengthAttribute>().Single(); int maxLen = strLenAttribute.MaximumLength; 
+12
source share

All Articles