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

.NET Core配置Swagger多集合(Web/Mobile)但UI为空的问题

Swagger多集合显示为空的问题排查与修复

我正在开发一款应用,需要为Web端和移动端配置Swagger多集合,但当前Swagger UI显示为空。以下是我的相关代码:

控制器代码

namespace RIOnlySelfCareService.Controllers
{
    [Route("api/web/[controller]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        private readonly IAccountService accountService;
        private readonly IMenuService _menuService;

        public AccountController(IAccountService accountService, IMenuService menuService)
        {
            this.accountService = accountService;
            _menuService = menuService;
        }

        [HttpPost("getMenus")]
        public async Task<IActionResult> GetMenusAsync()
        {
            return Ok(await _menuService.GetMenusAsync());
        }
    }
}

namespace RIOnlySelfCareService.Controllers.MobileControllers
{
    [Route("api/mobile/[controller]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        private readonly IAccountService accountService;
        private readonly IMenuService _menuService;

        public AccountController(IAccountService accountService, IMenuService menuService)
        {
            this.accountService = accountService;
            _menuService = menuService;
        }

        [HttpPost("getMenus")]
        public async Task<IActionResult> GetMenusAsync()
        {
            return Ok(await _menuService.GetMenusAsync());
        }
    }
}

Program.cs

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("web", new OpenApiInfo
    {
        Title = "Self Care Web API",
        Version = "v1"
    });
    c.SwaggerDoc("mobile", new OpenApiInfo
    {
        Title = "Self Care Mobile API",
        Version = "v1"
    });

    c.DocInclusionPredicate((docName, apiDesc) =>
    {
        // 检查控制器路由是否包含指定前缀
        if (apiDesc.TryGetMethodInfo(out MethodInfo methodInfo))
        {
            var controllerAttribute = methodInfo.DeclaringType?.GetCustomAttributes(true)
                .OfType<RouteAttribute>()
                .FirstOrDefault();

            if (controllerAttribute != null)
            {
                var routePrefix = controllerAttribute.Template.ToLower();

                // 根据路由前缀分组控制器
                if (docName == "web" && routePrefix.StartsWith("api/web"))
                    return true;

                if (docName == "mobile" && routePrefix.StartsWith("api/mobile"))
                    return true;
            }
        }

        return false;
    });
 }

if (!app.Environment.IsProduction())
{
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        // 为Web控制器渲染Swagger UI
        options.SwaggerEndpoint("/swagger/web/swagger.json", "Self Care Web API");
        // 为移动端控制器渲染Swagger UI
        options.SwaggerEndpoint("/swagger/mobile/swagger.json", "Self Care Mobile API");
    });
}

问题排查与修复方案

1. 修复语法错误

AddSwaggerGen配置代码末尾缺少闭合括号和分号,导致整个Swagger配置未正确加载,这是UI为空的核心原因:

// 原错误代码末尾
 }
// 修正后:
});

2. 优化路由匹配逻辑

原代码依赖控制器的RouteAttribute.Template判断前缀,但[controller]占位符会被实际控制器名替换,用ApiDescription.RelativePath判断更准确:

c.DocInclusionPredicate((docName, apiDesc) =>
{
    var relativePath = apiDesc.RelativePath?.ToLower();
    if (relativePath == null) return false;

    return (docName == "web" && relativePath.StartsWith("api/web")) ||
           (docName == "mobile" && relativePath.StartsWith("api/mobile"));
});

3. 检查中间件顺序

确保Swagger中间件放在正确的位置,必须在UseRouting之后、UseEndpoints之前:

app.UseRouting();

// 可添加认证、授权等中间件

if (!app.Environment.IsProduction())
{
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/web/swagger.json", "Self Care Web API");
        options.SwaggerEndpoint("/swagger/mobile/swagger.json", "Self Care Mobile API");
    });
}

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

4. 可选:添加XML注释(增强Swagger信息)

若需要Swagger显示接口注释,右键项目→属性→生成→勾选"XML文档文件",并在Swagger配置中添加:

var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 09:33:13