【问题标题】:How can I show custom annotations used in my models in Swashbuckle?如何在 Swashbuckle 中显示我的模型中使用的自定义注释?
【发布时间】:2020-01-09 14:15:15
【问题描述】:

我们在代码中使用 JetBrains 注释来定义对象模型的可空性行为。默认情况下,我无法在使用Swashbuckle.AspNetCore v5.0.0-rc5 实现的 Swagger UI 中看到这些,所以我假设默认情况下不支持这些。有没有办法添加这个功能?

仅供参考,我使用的是 ASP.NET Core WebApi 3.1。

例如:

public class Person {
   [NotNull]
   public Id PersonId{get; set;}

   [CanBeNull]
   public Address Address {get;set;}


}

【问题讨论】:

    标签: c# asp.net-core swagger swashbuckle


    【解决方案1】:

    创建一个自定义模式过滤器,例如(用您的逻辑扩展它):

    public class AssignPropertyRequiredFilter : ISchemaFilter
        {
            public void Apply(Schema schema, SchemaFilterContext context)
            {
                var requiredProperties = context.SystemType.GetProperties()
                    .Where(x => x.IsDefined(typeof(NotNullAttribute)))
                    .Select(t => char.ToLowerInvariant(t.Name[0]) + t.Name.Substring(1));
    
                if (schema.Required == null)
                {
                    schema.Required = new List<string>();
                }
                schema.Required = schema.Required.Union(requiredProperties).ToList();
            }
        }
    

    然后注册

    services.AddSwaggerGen(cfg => cfg.SchemaFilter<AssignPropertyRequiredFilter>());
    

    【讨论】:

    • 有些不对劲。首先, ISchemaFilter 具有以下签名:void Apply(OpenApiSchema schema, SchemaFilterContext context); 即使这样,您建议的 IsDefined 似乎也没有捕获 [NotNull] 。它甚至没有出现在 CustomAttributes 列表中。显然我错过了一些东西。
    • >> OpenApiSchema
    【解决方案2】:

    Roman Marusyk 给出了正确的答案,但我想详细说明我必须做些什么才能让它在我的设置中正常工作。

    本质上,JetBrains 注释是隐藏的,因为默认情况下没有打开条件编译标志

    [Conditional("JETBRAINS_ANNOTATIONS")]
    public sealed class NotNullAttribute : Attribute
    

    我通过将JETBRAINS_ANNOTATIONS 添加到我的编译符号列表中打开它并开始查看属性。一旦我明白了这一点,我就能够应用 Roman Marusyk 的逻辑大纲。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-16
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      相关资源
      最近更新 更多