gpt4 book ai didi

asp.net-core - 在运行时启用/禁用 SwaggerUI

转载 作者:行者123 更新时间:2023-12-05 02:40:57 24 4
gpt4 key购买 nike

我有 4 个环境开发、测试、暂存和生产。

我们必须仅为生产环境禁用 Swagger,但这应该是可配置的,如果我们愿意,我们也可以启用它,以防万一测试某些端点而无需再次构建应用程序。

Swagger 的这种启用和禁用应该在运行时的基础上完成,正如我提到的,我不想再次构建应用程序。

提前致谢。

最佳答案

我通过配置来控制它,例如在 appsettings.json 中。

{
"applicationSettings": {
"serviceName": "Test",
"swaggerUIEnabled": true
}
}

然后使用Swashbuckle.AspNetCore 如下配置Startup.cs :

public class Startup
{
private readonly IConfiguration _configuration;

public Startup(IConfiguration configuration)
{
_configuration = configuration;
}

public void ConfigureServices(IServiceCollection services)
{
services.AddSettings<ApplicationSettings>(_configuration.GetSection("applicationSettings"));

// ...

if (appSettings.SwaggerUIEnabled)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc(appSettings.ServiceName,
new OpenApiInfo
{
Title = appSettings.ServiceName,
Version = Assembly.GetEntryAssembly()?
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
.InformationalVersion ?? "NA"
});
});
}

// ...
}

public static void Configure(
IApplicationBuilder app,
IServiceProvider provider)
{
// ...

if (appSettings.SwaggerUIEnabled)
{
app.UseStaticFiles()
.UseSwagger()
.UseSwaggerUI(c =>
{
c.SwaggerEndpoint(Url.Combine("/", "swagger.json"), appSettings.ServiceName);
});
}

// ...
}
}

swaggerUIEnabled 配置设置在所有非生产环境中为 true,在生产环境中为 false

注意:您需要在 wwwroot 下静态托管您的 Open API 规范(上面代码示例中的 swagger.json)。

关于asp.net-core - 在运行时启用/禁用 SwaggerUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68357425/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com