从ModelValidator获取操作信息

| 我正在实现一个ModelValidator,该模型需要从执行操作中获取反映的信息。验证行为将根据装饰方式而变化。我可以得到这些信息吗?     
已邀请:
        ModelValidator的构造函数应采用ControllerContext。您可以使用该对象来确定控制器装饰了哪些属性,如下所示:
context.Controller.GetType().GetCustomAttributes(typeof(YourAttribute), true).Length > 0
编辑: 您还可以像这样获得所有属性的列表:
attributes = context.Controller.GetType().GetCustomAttributes(true);
因此,一个基于特定属性进行验证的简单示例:
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
        }
    }
}
}     
        反编译System.Web.Mvc后,我得到了它:
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);
}
    

要回复问题请先登录注册