3

属性を使用して Web API ヘルプ ページを生成するためのサンプルを提供する方法はありますか? /Areas/HelpPage/... にアクセスしてサンプルを提供できることはわかっていますが、すべてのサンプルをコードと共に 1 か所にまとめたいと考えています。

これらの行に沿ったもの:

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

1 に答える 1

3

これは、次のようなカスタム属性を自分で作成することで実現できます。

[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 が定義されているかどうかを確認するチェックを追加しました。定義されている場合は、自動生成された値の代わりにその値を使用します。

于 2015-04-29T10:13:59.453 に答える