Search code examples
swaggerasp.net-core-3.1swashbuckle.aspnetcore

ASP.Net Core 3.1 Swagger Page Loads via HTTPS but Try It Now uses HTTP and Browser Fails Request


I just upgraded my project from Swashbuckle 5.6.3 to 6.0.7. I have made no code changes, but now when attempting to use the Swagger page to test the API, the URL generated by Swagger is not using https even though the page is loaded through https and all the documentation I can find says that it should infer the scheme based on the URL used to load the Swagger page.

Here is the configuration code:

        services.AddSwaggerGen(c => {
            c.SwaggerDoc(apiSettings.Version, new OpenApiInfo { Title = apiSettings.Name, Version = apiSettings.Version });

            c.CustomSchemaIds(type => type.FullName);

            c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme {
                Description = "JWT Authorization header using the Bearer scheme.",
                Name        = "Authorization",
                In          = ParameterLocation.Header,
                Type        = SecuritySchemeType.ApiKey,
                Scheme      = "bearer",
                Reference   = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
            });

            c.AddSecurityRequirement(new OpenApiSecurityRequirement {
                { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new List<string>() }
            });
        });

and:

        app.UseSwagger();

        app.UseSwaggerUI(c => {
            c.SwaggerEndpoint($"/swagger/{apiSettings.Version}/swagger.json", $"{apiSettings.Name} {apiSettings.Version}");
        });

Is there a new configuration setting to specify the scheme now?


Solution

  • In the end, this is the final code that worked for me.

            app.UseEndpoints(endpoints => {
                endpoints.MapControllers();
    
                endpoints.MapSwagger("/swagger/{documentName}/swagger.json", options => {
                    options.PreSerializeFilters.Add((swagger, httpRequest) => { });
                });
            });