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

后端 未结 1 1289
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-10 15:50

I have some data annotation attribute like this:

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


        
相关标签:
1条回答
  • 2020-12-10 16:22

    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 a property from it:

    StringLengthAttribute strLenAttr = 
      typeof(Person).GetProperty("FirstName").GetCustomAttributes(
      typeof(StringLengthAttribute), false).Cast<StringLengthAttribute>().Single();
    
    
    int maxLen = strLenAttribute.MaximumLength;
    
    0 讨论(0)
提交回复
热议问题