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

ASP.NET Core 结合 Swagger 如何生成公开与内部两份 swagger.json

解决方案

你只需要新增一个自定义文档过滤器,按路由规则筛选接口到对应文档即可,操作步骤如下:


步骤1:实现自定义IDocumentFilter

新建过滤器类,代码如下:

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

public class SwaggerGroupFilter : IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        var currentDocVersion = swaggerDoc.Info.Version;
        // 遍历所有接口描述,过滤不符合当前文档分组的接口
        foreach (var apiDesc in context.ApiDescriptions)
        {
            var routePath = apiDesc.RelativePath?.ToLower() ?? string.Empty;
            var pathKey = "/" + apiDesc.RelativePath;

            // 内部文档仅保留路由含internal的接口
            if (currentDocVersion == "v1-internal")
            {
                if (!routePath.Contains("internal"))
                {
                    swaggerDoc.Paths.Remove(pathKey);
                }
            }
            // 公开文档排除所有含internal的接口
            else if (currentDocVersion == "v1")
            {
                if (routePath.Contains("internal"))
                {
                    swaggerDoc.Paths.Remove(pathKey);
                }
            }
        }
    }
}

该过滤器会自动识别Controller层级、Action层级路由中包含的internal关键字,不需要额外修改接口的特性标记。


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

修改你Startup里ConfigureServices的SwaggerGen配置,添加过滤器注册:

services.AddSwaggerGen(gen =>
{
    gen.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "Server API",
        Version = "1.0",
        Description = "This API features all public available endpoints showing different API features."
    });
    gen.SwaggerDoc("v1-internal", new OpenApiInfo
    {
        Title = "Viewer Server API (internal)",
        Version = "v1-internal",
        Description = "This API features all public available endpoints showing different API features."
    });
    // 新增这一行,注册刚才写的分组过滤器
    gen.DocumentFilter<SwaggerGroupFilter>();
});

验证效果

启动项目后打开SwaggerUI,切换不同的端点:

  • 选择Viewer Server API v1时,仅展示无internal关键字的公开路由接口
  • 选择Viewer Server API v1 (internal)时,仅展示路由含internal的内部接口

你原有的Configure方法里的Swagger中间件配置不需要修改。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 17:33:01