ASP.NET WebApi 2 Text Attribute Sample

Is there a way to provide samples for creating api api help pages using attributes? I know I can provide samples by going to / Areas / HelpPage / ... but I want them all in the same place with my code.

Something like this:

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

      

+3


source to share


1 answer


This can be achieved by creating a custom attribute yourself, something like:

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

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

      

And then changing the method SetPublicProperties

ObjectGenerator

like this:



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);
            }
        }
    }

      

I added a check to determine if the TextSampleAttribute is defined and if it uses that value instead of the auto-generated one.

+3


source







All Articles