繁体   English   中英

ASP.Net WebApi 2示例文本属性

[英]ASP.Net WebApi 2 sample text attribute

有没有办法为使用属性的web api帮助页面生成提供样本? 我知道我可以通过转到/ Areas / HelpPage / ...来提供样本,但是我希望它们都能在我的代码中放在一个地方。

这些方面的东西:

    /// <summary>
    /// userPrincipalName attribute of the user in AD
    /// </summary>
    [TextSample("john.smith@contoso.com")]
    public string UserPrincipalName;

这可以通过自己创建自定义属性来实现,例如:

[AttributeUsage(AttributeTargets.Property)]
public class TextSampleAttribute : Attribute
{
    public string Value { get; set; }

    public TextSampleAttribute(string value)
    {
        Value = value;
    }
}

然后修改SetPublicProperties的方法ObjectGenerator这样的:

private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
    {
        PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
        ObjectGenerator objectGenerator = new ObjectGenerator();
        foreach (PropertyInfo property in properties)
        {
            if (property.IsDefined(typeof (TextSampleAttribute), false))
            {
                object propertyValue = property.GetCustomAttribute<TextSampleAttribute>().Value;
                property.SetValue(obj, propertyValue, null);
            }
            else if (property.CanWrite)
            {
                object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
                property.SetValue(obj, propertyValue, null);
            }
        }
    }

我添加了一个检查以查看TextSampleAttribute是否已定义,如果是,则使用它的值而不是自动生成的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM