我希望在开发和登台期间启用 SwaggerUI,但在生产环境中禁用。
我已经遵循了这个代码:
appsettings.json "AppSettings": { "SwaggerEnabledSettings": true, }
程序.cs
if (app.Environment.IsDevelopment() || app.Environment.IsProduction())
{
app.UseSwaggerAuthorized();
app.UseDeveloperExceptionPage();
app.UseSwagger();
if (swaggerEnabled)
{
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyAPI V1");
c.RoutePrefix = "";
});
}
}
在上面的代码在本地环境中正常工作时,我已经将我的应用程序配置为从 appsettings.json 读取 SwaggerEnabledSettings 以确定是否应该启用 SwaggerUI。目前,我需要重新启动应用程序才能使此设置中的更改生效。但是,我需要帮助来确保此配置动态影响 SwaggerUI 的行为,而不需要重新启动应用程序。
您可以使用自定义中间件来实现您的要求:
创建 AppSettings 类:
public class AppSettings
{
public bool SwaggerEnabledSettings { get; set; }
}
程序.cs:
builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
app.UseMiddleware<SwaggerMiddleware>();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyAPI V1");
c.RoutePrefix = "";
});
动态中间件:
public class SwaggerMiddleware
{
private readonly RequestDelegate _next;
private readonly IWebHostEnvironment _env;
public SwaggerMiddleware(RequestDelegate next, IWebHostEnvironment env)
{
_next = next;
_env = env;
}
public async Task InvokeAsync(HttpContext context, IOptionsSnapshot<AppSettings> settings)
{
if ((_env.IsDevelopment() || _env.IsStaging()) && settings.Value.SwaggerEnabledSettings)
{
if (context.Request.Path.StartsWithSegments("/swagger"))
{
await _next(context);
return;
}
}
await _next(context);
}
}