3

Есть ли способ предоставить образцы для создания страниц справки api api с использованием атрибутов? Я знаю, что могу предоставить образцы, перейдя в/Areas/HelpPage/... , но я хочу, чтобы все они были в одном месте с моим кодом.ASP.Net WebApi 2 образец текстового атрибута

Что-то вдоль этих линий:

/// <summary> 
    /// userPrincipalName attribute of the user in AD 
    /// </summary> 
    [TextSample("[email protected]")] 
    public string UserPrincipalName; 

ответ

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

Я добавил чек, чтобы увидеть i f Определен атрибут TextSampleAttribute, и если это так, используйте его вместо автоматического сгенерированного.

Смежные вопросы