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

如何为ASP.NET Core Web API生产环境设置Swagger启动路径

ASP.NET Core 3.1 Web API 生产环境配置Swagger默认启动路径方案

1. 配置appsettings.json参数

在appsettings.json中添加Swagger相关配置节点,支持灵活控制生产环境Swagger启用状态和默认启动路径:

{
  "Swagger": {
    "EnableInProduction": true,
    "DefaultLaunchPath": "/swagger"
  },
  // 保留原有配置项不变
}

2. 修改Startup.cs中间件逻辑

ASP.NET Core 3.1默认仅在开发环境启用Swagger,需要手动调整生产环境的启用逻辑,同时添加根路径重定向规则。

2.1 注册Swagger生成服务

在ConfigureServices方法中保持Swagger生成器的注册:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "你的接口名称", Version = "v1" });
    });
    // 其他服务注册逻辑不变
}

2.2 配置中间件管道

在Configure方法中读取配置、放开生产环境Swagger限制、添加默认路径重定向:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IConfiguration configuration)
{
    // 读取appsettings中的Swagger配置
    bool enableSwagger = env.IsDevelopment() || configuration.GetValue<bool>("Swagger:EnableInProduction");
    string launchPath = configuration.GetValue<string>("Swagger:DefaultLaunchPath");

    if (enableSwagger)
    {
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "你的接口名称 V1");
            // 若需要根路径直接访问Swagger,取消下一行注释,同时将appsettings中DefaultLaunchPath改为"/"
            // c.RoutePrefix = string.Empty;
        });

        // 根路径默认重定向到Swagger页面
        app.Use(async (context, next) =>
        {
            if (context.Request.Path == "/")
            {
                context.Response.Redirect(launchPath);
                return;
            }
            await next();
        });
    }

    // 原有中间件配置不变,比如路由、授权、端点映射等
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

注意事项

  • 生产环境开启Swagger建议添加身份校验逻辑,避免接口文档未授权暴露
  • 若站点部署在虚拟目录下,需将SwaggerEndpoint路径改为相对路径./v1/swagger.json适配部署场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 17:36:01