You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Swashbuckle隐藏Swagger UI中.NET Core接口基类的Schema

解决方案

你可以通过Swashbuckle提供的过滤器机制实现需求,以下是具体实现步骤:


步骤1:添加自定义过滤器

1.1 实现Schema过滤器,过滤基类Schema生成

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

public class HideDefaultCommandResultSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        // 匹配所有DefaultCommandResult泛型类型,直接从Schema仓库中移除
        if (context.Type.IsGenericType && context.Type.GetGenericTypeDefinition() == typeof(DefaultCommandResult<>))
        {
            context.SchemaRepository.Schemas.Remove(context.Type.Name);
        }
    }
}

1.2 实现Document过滤器,替换响应关联的基类引用

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

public class ReplaceBaseResponseFilter : IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        // 遍历所有接口响应,移除关联的基类Schema引用
        foreach (var pathItem in swaggerDoc.Paths.Values)
        {
            foreach (var operation in pathItem.Operations.Values)
            {
                foreach (var response in operation.Responses.Values)
                {
                    if (response.Content == null) continue;
                    foreach (var contentItem in response.Content.Values)
                    {
                        var refId = contentItem.Schema?.Reference?.Id;
                        if (refId != null && refId.StartsWith("DefaultCommandResult"))
                        {
                            contentItem.Schema.Reference = null;
                        }
                    }
                }
            }
        }

        // 最后清理所有残留的基类Schema
        var baseSchemaKeys = swaggerDoc.Components.Schemas.Keys
            .Where(k => k.StartsWith("DefaultCommandResult"))
            .ToList();
        foreach (var key in baseSchemaKeys)
        {
            swaggerDoc.Components.Schemas.Remove(key);
        }
    }
}

步骤2:注册过滤器到Swagger配置

在Startup.cs的ConfigureServices方法中,修改Swagger注册逻辑:

services.AddSwaggerGen(options =>
{
    // 你的原有Swagger配置,比如SwaggerDoc、注释导入等

    // 注册自定义过滤器
    options.SchemaFilter<HideDefaultCommandResultSchemaFilter>();
    options.DocumentFilter<ReplaceBaseResponseFilter>();

    // 可选:配置泛型类型的Schema名称,避免生成混乱的泛型标识
    options.CustomSchemaIds(type =>
    {
        if (!type.IsGenericType) return type.Name;
        var genericTypeName = type.GetGenericTypeDefinition().Name.Split('`')[0];
        var genericArgs = string.Join(",", type.GetGenericArguments().Select(t => t.Name));
        return $"{genericTypeName}<{genericArgs}>";
    });
});

可选优化:接口标注实际返回类型

你也可以在接口上添加[ProducesResponseType]特性,直接指定每个状态码对应的实际返回类型,Swagger会优先读取该配置,不会再关联基类Schema:

[ProducesResponseType(typeof(SuccessCommandResult<ServerIdCommand>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ErrorCommandResult<string>), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ErrorCommandResult<string>), StatusCodes.Status400BadRequest)]
public ActionResult<DefaultCommandResult<ServerIdCommand>> Get([FromQuery] RecoverServerIdCommand command)
{
    // 原有接口逻辑
}

可选清理

如果不需要展示多态继承关系,可以移除DefaultCommandResult上的[SwaggerSubType]特性,以及子类上的[SwaggerDiscriminator]特性,避免Swagger生成多余的关联引用。

内容的提问来源于stack exchange,提问作者Felipe CS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 00:21:00