-1

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?

4

2 回答 2

1

您的 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
        }
    }
}

}

于 2011-06-18T18:20:13.623 回答
0

反编译 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);
}
于 2011-06-19T00:05:52.187 回答