Enable/Disable SwaggerUI in ASP.NET Web API Based on Environment

57 Views Asked by At

I want SwaggerUI to be enabled during development and staging but disabled in the production environment.

I have follow this code: appsettings.json "AppSettings": { "SwaggerEnabledSettings": true, } programme.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 = "";          
 });     
} 
} 

In above code working fine in local environment I have already configured my application to read the SwaggerEnabledSettings from appsettings.json to determine whether SwaggerUI should be enabled or not. currently, I need to restart the application for changes in this setting to take effect. However, I need assistance in ensuring that this configuration dynamically affects the behavior of SwaggerUI without requiring a restart of the application.

1

There are 1 best solutions below

4
Jalpa Panchal On

You could use custom middleware to achieve your requirement:

create class AppSettings:

public class AppSettings
{
    public bool SwaggerEnabledSettings { get; set; }
}

Program.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 = "";
});

DynamicMiddleware:

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);
    }
}

program.cs:

var builder = WebApplication.CreateBuilder(args);

// Configure services here
builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
builder.Services.AddSingleton<SwaggerMiddleware>(); // If needed

var app = builder.Build();

if (!app.Environment.IsProduction())
{
    app.UseMiddleware<SwaggerMiddleware>(); 
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyAPI V1");
        c.RoutePrefix = "";
    });
}

// Other middleware

app.Run();