如何在Swashbuckle中展示模型所用的JetBrains可空性注解?
如何让Swashbuckle.AspNetCore v5.0.0-rc5识别JetBrains可空注解?
没问题,我刚好处理过类似的场景!Swashbuckle.AspNetCore 默认确实不支持 JetBrains 的 [NotNull]/[CanBeNull] 注解,不过我们可以通过自定义一个Schema过滤器来让Swagger UI正确识别这些注解定义的可空性行为,完美适配你的ASP.NET Core 3.1 WebApi项目。
步骤1:确保安装JetBrains注解包
首先确认你的项目已经引用了JetBrains.Annotations NuGet包,如果没有的话,通过以下命令安装:
# 使用Package Manager Console Install-Package JetBrains.Annotations # 或者使用.NET CLI dotnet add package JetBrains.Annotations
步骤2:创建自定义Schema过滤器
新建一个类,实现Swashbuckle的ISchemaFilter接口,在这个过滤器里检查属性上的JetBrains注解,然后修改Swagger Schema的可空设置:
using JetBrains.Annotations; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System.Reflection; public class JetBrainsNullableSchemaFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { // 处理类型本身的注解(如果需要) if (context.Type.GetCustomAttribute<CanBeNullAttribute>() != null) { schema.Nullable = true; } else if (context.Type.GetCustomAttribute<NotNullAttribute>() != null) { schema.Nullable = false; } // 处理属性的注解 foreach (var property in context.Type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { var propertyName = context.ApiExplorerSettings?.GroupName != null ? property.Name : schema.Properties.Keys.FirstOrDefault(k => k.Equals(property.Name, StringComparison.OrdinalIgnoreCase)); if (propertyName == null || !schema.Properties.TryGetValue(propertyName, out var propertySchema)) continue; if (property.GetCustomAttribute<CanBeNullAttribute>() != null) { propertySchema.Nullable = true; } else if (property.GetCustomAttribute<NotNullAttribute>() != null) { propertySchema.Nullable = false; } } } }
步骤3:在Swagger配置中注册过滤器
打开Startup.cs的ConfigureServices方法,在AddSwaggerGen里添加这个自定义过滤器:
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API", Version = "v1" }); // 注册JetBrains注解过滤器 c.SchemaFilter<JetBrainsNullableSchemaFilter>(); });
额外注意事项
- 如果你同时启用了C# 8的可空引用类型(在项目文件里设置
<Nullable>enable</Nullable>),这个过滤器会和内置的可空处理逻辑兼容,优先遵循JetBrains注解的设置。 - 确保你的Swashbuckle.AspNetCore版本确实是v5.0.0-rc5,这个过滤器是针对该版本的OpenAPI 3.0规范编写的。
内容的提问来源于stack exchange,提问作者Milan
相关产品推荐
相关产品推荐

