Search code examples
.netasp.net-coreswaggerswagger-uiswashbuckle.aspnetcore

Swagger settings to solve mixed content error


I have a dotnet core web api that is documented by swagger. Here is how I set it up:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddHealthChecks();
        services.AddSingleton(sp =>
        {
            var options = new JsonSerializerOptions();
            options.Converters.Add(new DateTimeOffsetConverter());
            options.Converters.Add(new LabelDataConverter());
            return options;
        });
        services.AddCacheManager(Configuration);
        services.AddKafkaConsumers(Configuration);

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "X.WebApi", Version = "v1" });
        });
        
        services.AddInfluxDb(options => Configuration.GetSection("InfluxDb").Bind(options));
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "X.WebApi v1"));

        app.UseRouting();

        app.UseAuthorization();

        app.UseHealthChecks("/health");

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });            
    }

I can run the endpoints by swagger ui on my local machine but when I deploy the application to server I'm getting TypeError: Failed to fetch errors. Here is what I see on browser's console:

swagger-ui-bundle.js:2 Mixed Content: The page at 'https://x.y.consul.z.com/swagger/index.html' was loaded over HTTPS, but requested an insecure resource 'http://x.y.consul.z.com/v1/Path/1'. This request has been blocked; the content must be served over HTTPS.

How should I update the swagger settings to be able to run without issue also on the server?


Solution

  • You can add HTTPS as a scheme to your swagger UI to workaround this issue: https://swagger.io/docs/specification/2-0/api-host-and-base-path/