How to get a list of implementation rules - FluentValidations

Using FluentValidation with WebAPI, I'm trying to show the rules implemented in a property.

I am using assemblies Microsoft.AspNet.WebApi.HelpPage which will generate help pages for my API. I would like to be able to enumerate the validation rules so that I can display the attributes as required and the length in the help pages.

I used to do this for a custom attribute with something like the following:

-- 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" }
    };

      

This will add the text needed in the more information section of the help page. In the case of using FluentValidation, the required type is no longer set. Now it is something likeRuleFor(x => x.MyProperty).NotEmpty();

If useful, the code documenting the annotations is below:

-- 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);
    }
}

      

When calling this GenerateAnnotations procedure, I would like to add logic that will look at the property and get all available attributes and add text.

Perhaps somehow use FluentValidation.Internal.PropertyRules to list the attributes gracefully?

+3


source to share





All Articles