I'm implementing a ModelValidator that needs to get reflected information from the executing action. Validation behavior will change depending on how action is decorated. Can I get that information?
Asked
Active
Viewed 212 times
2 Answers
1
The constructor for your ModelValidator should take a ControllerContext. You can use that object to determine what attributes your controller is decorated with like so:
context.Controller.GetType().GetCustomAttributes(typeof(YourAttribute), true).Length > 0
Edit:
You can also get a list of all attributes like so:
attributes = context.Controller.GetType().GetCustomAttributes(true);
So, a simple example for validating based on a specific attribute:
public class SampleValidator : ModelValidator {
private ControllerContext _context { get; set; }
public SampleValidator(ModelMetadata metadata, ControllerContext context,
string compareProperty, string errorMessage) : base(metadata, context) {
_controllerContext = context;
}
public override IEnumerable<ModelValidationResult> Validate(object container) {
if (_context.Controller.GetType().GetCustomAttributes(typeof(YourAttribute), true).Length > 0) {
// do some custom validation
}
if (_context.Controller.GetType().GetCustomAttributes(typeof(AnotherAttribute), true).Length > 0) {
// do something else
}
}
}
}

gram
- 2,772
- 20
- 24
-
We are almost there. I need to get what attributes the executing action is decorated with. – Eduardo Jun 18 '11 at 18:34
-
That returns all attributes of controller. Which method? – Eduardo Jun 18 '11 at 18:58
-
I'm not sure what you're asking. I updated my answer to show a simple example of how this might work. – gram Jun 18 '11 at 19:12
-
Instead of _context.Controller I need to implement getExecutingActionMethodInfo() in this example: MethodInfo info = getExecutingActionMethodInfo(); if (info.GetCustomAttributes(typeof(YourAttribute), true).Length > 0) ... – Eduardo Jun 18 '11 at 22:02
0
After decompiling System.Web.Mvc I got it:
protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
{
ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(context.Controller.GetType());
ReflectedActionDescriptor actionDescriptor = (ReflectedActionDescriptor) controllerDescriptor.FindAction(context, context.RouteData.GetRequiredString("action"));
object[] actionAttributes = actionDescriptor.GetCustomAttributes(typeof(MyAttribute), true);
}

Eduardo
- 5,645
- 4
- 49
- 57
-
Eduardo: regarding your moderator response, you don't have to put your entire blog entry in your answer. Just summarize the important details of your blog entry, and provide a link. Answers with bare links (without a summary) suffer from several problems; they look like spam, and they suffer from link rot. – Robert Harvey Jun 22 '11 at 14:31