Skip to main content

ELL Blog

ASP.NET Core Swagger Dark Theme

For the SEO: How to add dark theme to Swagger UI ASP.NET? Follow these instructions.

If you have guidelines for other frameworks, feel free to email me your code so I can add it to the README.md

There’s two ways to accomplish this. One is to use serve static files and the other is to only serve the static file (through embedded resource). I’ll give instructions just in case.

Serving From Static Folder

Create ProjectName/wwwroot/css/SwaggerDark.json in your project. You need to create these folders if they do not exist. If you have guidelines for other frameworks, feel free to email me your code so I can add it to the README.md

In Program.cs:

app.UseStaticFiles();  // ADD THIS LINE
if (app.Environment.IsDevelopment()) {
            app.UseHttpLogging();
            app.UseSwagger();
            app.UseSwaggerUI(c => {
                c.EnableTryItOutByDefault();
                c.InjectStylesheet("/css/SwaggerDark.css");  // ADD THIS LINE
            });
        }

Serving From an Embedded Resource

I don’t really recommend this route anymore, as it adds complexity for serving static files.

Create ProjectName/Assets/SwaggerDark.json in your project. You need to create the asset folder if it does not exist.

In Program.cs:

using System.Reflection;

if (app.Environment.IsDevelopment()) {
            app.UseHttpLogging();
            app.UseSwagger();
            app.UseSwaggerUI(c => {
                c.EnableTryItOutByDefault();
                c.InjectStylesheet("/css/SwaggerDark.css");  // ADD THIS LINE
            });
            // add this:
            app.MapGet("/css/SwaggerDark.css", () => {
                var assembly = Assembly.GetExecutingAssembly();
                // SttApi to ProjectName
                return Results.Stream(assembly.GetManifestResourceStream("SttApi.Assets.SwaggerDark.css")!, "text/css");
            }).ExcludeFromDescription();
        }

In ProjectName/ProjectName.csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">
    <!-- ... -->
    <ItemGroup>
        <!-- other embedded resources -->
        <EmbeddedResource Include="Assets/SwaggerDark.css" />
    </ItemGroup>
    <!-- ... -->
</Project>

You may need to hard restart your app for the changes to take effect.

Screenshot 1 of Swagger Dark Theme

Screenshot 2 of Swagger Dark Theme