Checking attributes from other attribute code

Can I check for an attribute in the code of another attribute?

Let's say you have the following class definition:

public class Inception { [Required] [MyTest] public int Levels { get; set; } } public class MyTestAttribute : ValidationAttribute { public override bool IsValid(object o){ // return whether the property on which this attribute // is applied also has the RequiredAttribute } } 

... is it possible for MyTestAttribute.IsValid to determine if Inception.Levels has RequiredAttribute?

+6
source share
1 answer

In the specific case of ValidationAttribute this is possible, but you should use another IsValid overload, which has a context parameter. The context can be used to get the containing type, and also to get the name of the property to which the attribute applies.

 protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var requiredAttribute = validationContext.ObjectType .GetPropery(validationContext.MemberName) .GetCustomAttributes(true).OfType<RequiredAttribute>().SingleOrDefault(); } 
+3
source

Source: https://habr.com/ru/post/915937/


All Articles