3

FluentValidationを WebAPI で使用して、プロパティに実装されているルールを表示しようとしています。

API のヘルプ ページを生成する Microsoft.AspNet.WebApi.HelpPage アセンブリを使用しています。検証ルールを列挙して、必要な属性や長さなどの属性をヘルプ ページに表示できるようにしたいと考えています。

以前は、次のようなカスタム属性に対してこれを行っていました。

-- namespace MyAPI.Areas.HelpPage.ModelDescriptions

private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator =
    new Dictionary<Type, Func<object, string>>
    {
        { typeof(MyAttribute), a => "My Attribute Documentation" }
    };

これにより、ヘルプ ページの追加情報セクションに必要なテキストが追加されます。FluentValidationを使用する場合、必要な型が設定されなくなりました。それは今のようなものですRuleFor(x => x.MyProperty).NotEmpty();

役立つ場合は、注釈を文書化するコードを以下に示します。

-- namespace MyAPI.Areas.HelpPage.ModelDescriptions
/// <summary>   Generates the annotations. </summary>
/// <param name="property">         The property. </param>
/// <param name="propertyModel">    The property model. </param>
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
    var annotations = new List<ParameterAnnotation>();

    var attributes = property.GetCustomAttributes();
    foreach (var attribute in attributes)
    {
        Func<object, string> textGenerator;
        if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
        {
            annotations.Add(
                new ParameterAnnotation
                {
                    AnnotationAttribute = attribute,
                    Documentation = textGenerator(attribute)
                });
        }
    }

    // Rearrange the annotations
    annotations.Sort(
        (x, y) =>
        {
            // Special-case RequiredAttribute so that it shows up on top
            if (x.AnnotationAttribute is RequiredAttribute)
            {
                return -1;
            }
            if (y.AnnotationAttribute is RequiredAttribute)
            {
                return 1;
            }

            // Sort the rest based on alphabetic order of the documentation
            return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
        });

    foreach (var annotation in annotations)
    {
        propertyModel.Annotations.Add(annotation);
    }
}

この GenerateAnnotations ルーチンを呼び出すときに、プロパティを確認し、割り当てられたすべての流暢な属性を取得してテキストを追加するロジックを追加したいと考えています。

FluentValidation.Internal.PropertyRulesを何らかの方法で使用して、属性をエレガントに列挙することはできますか?

4

0 に答える 0