-1

実行中のアクションから反映された情報を取得する必要がある ModelValidator を実装しています。アクションがどのように装飾されているかによって、検証の動作が変わります。その情報を入手できますか?

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 に答える