Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net WebApi 2 sample text attribute

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

Something along these lines:

    /// <summary>
    /// userPrincipalName attribute of the user in AD
    /// </summary>
    [TextSample("[email protected]")]
    public string UserPrincipalName;
like image 899
Slavomír Današ Avatar asked Apr 08 '26 13:04

Slavomír Današ


1 Answers

This could 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 modifying the SetPublicProperties method of 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've added a check to see if the TextSampleAttribute is defined and if so use it's value instead of the auto-generated one.

like image 142
Robban Avatar answered Apr 10 '26 02:04

Robban