C# 如何获取实现规则列表-FluentValidations
使用WebAPI,我试图显示在属性上实现的规则 我正在使用Microsoft.AspNet.WebApi.HelpPage程序集,该程序集将为我的API生成帮助页。我希望能够枚举验证规则,以便在帮助页面上显示属性,如required和length 在前面,我将对自定义属性执行以下操作:C# 如何获取实现规则列表-FluentValidations,c#,asp.net-web-api,fluentvalidation,asp.net-web-api-helppages,C#,Asp.net Web Api,Fluentvalidation,Asp.net Web Api Helppages,使用WebAPI,我试图显示在属性上实现的规则 我正在使用Microsoft.AspNet.WebApi.HelpPage程序集,该程序集将为我的API生成帮助页。我希望能够枚举验证规则,以便在帮助页面上显示属性,如required和length 在前面,我将对自定义属性执行以下操作: -- namespace MyAPI.Areas.HelpPage.ModelDescriptions private readonly IDictionary<Type, Func<object,
-- 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" }
};
当调用这个GenerateAnnotations例程时,我想添加一个逻辑,它将查看属性并获得所有指定的fluent属性,然后添加文本
也许可以用这个来优雅地列举属性
-- 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);
}
}