将FluentValidation与WebAPI一起使用,我试图显示在属性上实现的规则。
我正在使用Microsoft.AspNet.WebApi.HelpPage程序集,它将为我的API生成帮助页面。我希望能够枚举验证规则,以便在帮助页面上显示所需的属性和长度。
以前,我会使用以下内容为自定义属性执行此操作:
-- 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来优雅地枚举属性?