【问题标题】:Getting hold of custom attribute property decorations in a Swashbuckle document filter在 Swashbuckle 文档过滤器中获取自定义属性属性装饰
【发布时间】:2022-04-23 08:33:15
【问题描述】:

我在 .net 5.0 项目中使用 Swashbuckle 6.1.4。

我想自定义模式中元素的顺序。默认顺序(即声明属性的顺序)不好,因为当模型扩展基本模型时,基本模型的属性列在底部。

我已成功应用文档过滤器按字母顺序对属性进行排序:

public class SchemaSortingFilter : IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        var descs = context.ApiDescriptions.ToList();

     // only applying to the SupporterDTO for now...
        string model = "SupporterDTO";
        if (swaggerDoc.Components.Schemas.ContainsKey(model))
        {
            var props = swaggerDoc.Components.Schemas[model].Properties.OrderBy(x => x.Key).ToArray();
            swaggerDoc.Components.Schemas[model].Properties.Clear();
            foreach (var prop in props)
            {
                swaggerDoc.Components.Schemas[model].Properties.Add(prop.Key, prop.Value);
            }
        }
    }
}

但我真正想要的是使用自定义属性来管理订单。像这样:

public class SwaggerOrderAttribute : Attribute
{
   public int Order { get; private set; }

   public SwaggerOrderAttribute(int order)
   {
      Order = order;
   }
}

我会用它来装饰属性:

[SwaggerOrder(1)]
String PropertyZ {get; set;}
[SwaggerOrder(3)]
String PropertyX {get; set;}
[SwaggerOrder(2)]
String PropertyY {get; set;}

我的问题是通过 swaggerDoc.Components.Schemas[model].Properties 在我的过滤器中公开的属性值列表不包括我的自定义属性。

在我的探索过程中,感谢this question 中的提示,我试图像这样抓住它们,但它没有看到它们:

if (apiDesc.TryGetMethodInfo(out MethodInfo mi))
{
   var atts = mi.DeclaringType
                .GetCustomAttributes(true)
                .OfType<SwaggerOrderAttribute>()
                .ToList();
}

如何引入我的自定义属性以包含在我的排序 linq 查询中?

【问题讨论】:

    标签: swagger swashbuckle swashbuckle.aspnetcore


    【解决方案1】:

    您需要实现ISchemaFilter。然后你就可以从MemberInfo获取自定义属性:

    context.MemberInfo.CustomAttributes
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-20
      • 2019-02-01
      • 1970-01-01
      • 2018-11-21
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多