I'm implementing a ModelValidator that needs to get reflected information from the executing action. Validation behavior will change dependi开发者_开发知识库ng on how action is decorated. Can I get that information?
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
}
}
}
}
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);
}
精彩评论