【问题标题】:ASP.Net WebApi 2 sample text attributeASP.Net WebApi 2 示例文本属性
【发布时间】:2015-04-17 15:35:44
【问题描述】:

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

类似的东西:

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

【问题讨论】:

    标签: c# asp.net asp.net-web-api asp.net-web-api2 asp.net-web-api-helppages


    【解决方案1】:

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

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

    然后像这样修改ObjectGeneratorSetPublicProperties方法:

    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,如果是,则使用它的值而不是自动生成的值。

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-30
      相关资源
      最近更新 更多