如何在 Swashbuckle 中显示我的模型中使用的自定义注释?

How can I show custom annotations used in my models in Swashbuckle?

我们在代码中使用 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;}


}

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

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

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

本质上,JetBrains 注释是隐藏的,因为默认情况下未启用的条件编译标志

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

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