Search code examples
.net-coreswagger

Middleware is Not Being Invoked By Swagger UI's index.html


I have a .NET 6.0 application with the Swashbuckle library installed. I wanted to enforce CSP in the response header whenever the index.html page is opened, but for some reason the InvokeAsync(HttpContext context) method is not being invoked.

If I try to use /swagger/index.html the method gets invoked, but when I switch back to /index.html it does not.

// Program.cs   
app.UseSwagger();
app.UseSwaggerUI(setupAction =>
{
    setupAction.RoutePrefix = string.Empty;
});

app.UseLoggingMiddleware();
...


// LoggingMiddleware.cs
public async Task InvokeAsync(HttpContext context)
{
    context.Response.Headers.Add("Content-Security-Policy", "default-src 'self';");
    await _next(context);
}

public static class LoggingMiddlewareExtensions 
{
    public static IApplicationBuilder UseLoggingMiddleware(this IApplicationBuilder builder) 
    {
        return builder.UseMiddleware<LoggingMiddleware>();
    }
}

Can anyone help me with this?


Solution

  • Each middleware registered in .net, executed in order from top to bottom. In order to make it work. You need to use the LoggingMiddleware before swagger.

    app.UseLoggingMiddleware(); // <- Should Be Here!!
    
    app.UseSwagger();
    app.UseSwaggerUI(setupAction =>
    {
        setupAction.RoutePrefix = string.Empty;
    });
    
    // app.UseLoggingMiddleware(); // Not Here!!