.NET 5/6/7环境下如何在Swagger UI中隐藏ProblemDetails Schema
隐藏Swagger UI中AspNetCore.Mvc.ProblemDetails Schema的实现方法
适用于.NET 5 / .NET 6 / .NET 7 开发环境,默认基于官方Swashbuckle.AspNetCore组件实现Swagger能力。
问题展示示意图:
实现方案
方案1:使用内置方法直接排除类型(推荐,适用于Swashbuckle.AspNetCore v6.0+)
直接在Swagger服务注册逻辑中添加SuppressType配置即可:
// .NET 6+ 顶级语句Program.cs 示例 builder.Services.AddSwaggerGen(options => { // 你原有其他Swagger配置,比如文档标题、版本、JWT认证配置等 // 增加本行配置禁止生成ProblemDetails的Schema options.SuppressType<Microsoft.AspNetCore.Mvc.ProblemDetails>(); }); // .NET 5 Startup.cs ConfigureServices 示例 services.AddSwaggerGen(options => { // 原有配置 options.SuppressType<Microsoft.AspNetCore.Mvc.ProblemDetails>(); });
方案2:自定义Schema过滤器(兼容所有Swashbuckle.AspNetCore版本)
如果你的Swashbuckle.AspNetCore版本较低没有内置SuppressType方法,可以通过自定义过滤器实现:
- 新增过滤器类
using Swashbuckle.AspNetCore.SwaggerGen; using Microsoft.OpenApi.Models; using Microsoft.AspNetCore.Mvc; public class RemoveProblemDetailsSchemaFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { // 当匹配到ProblemDetails类型时,从Schema仓库中移除对应条目 if (context.Type == typeof(ProblemDetails)) { context.SchemaRepository.Schemas.Remove(nameof(ProblemDetails)); } } }
- 注册过滤器到Swagger配置中
builder.Services.AddSwaggerGen(options => { // 原有其他Swagger配置 options.SchemaFilter<RemoveProblemDetailsSchemaFilter>(); });
注意事项
- 如果你使用NSwag组件实现Swagger能力,对应配置为在
AddOpenApiDocument/AddSwaggerDocument方法的配置项中添加ExcludedTypeNames = new List<string> { "ProblemDetails" }即可。 - 配置完成后建议清理浏览器缓存后重启项目,避免旧的Swagger UI缓存导致配置不生效。
- 该配置仅隐藏Schema列表的展示,不会影响接口异常时实际返回ProblemDetails结构的正常功能。
内容的提问来源于stack exchange,提问作者Kraego
相关产品推荐
相关产品推荐

