解决混合内容错误的Swagger设置

Swagger settings to solve mixed content error

我有一个由 swagger 记录的 dotnet 核心网络 api。 以下是我的设置方式:

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

我可以 运行 在我的本地计算机上通过 swagger ui 端点,但是当我将应用程序部署到服务器时,我收到 TypeError: Failed to fetch 错误。这是我在浏览器控制台上看到的内容:

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.

我应该如何更新 swagger 设置才能 运行 在服务器上也没有问题?

部署后,您的应用程序是否使用代理服务器、负载平衡器等在 HTTPS 中公开?

如果是,那你的问题可能不是Swagger本身,而是转HTTP的时候丢掉了原来的HTTPS方案。事实上,请检查您是否可以调用您的 API.

在这种情况下,解决方案可能如文档所述here。 (请检查一下,因为中间件的顺序等有一些调整。)

简而言之,你可以这样尝试:

public void ConfigureServices(IServiceCollection services)
{
    // Configure this as suited for your case
    services.Configure<ForwardedHeadersOptions>(options =>
    {
        // Processing all forward headers (the default is None)
        options.ForwardedHeaders = ForwardedHeaders.All;

        // Clearing known networks and proxies collections
        options.KnownNetworks.Clear(); 
        options.KnownProxies.Clear();
    });
    // ...
}

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

    // If you only specify this and don't perform the configuration
    // in "ConfigureServices", the default configuration is used
    app.UseForwardedHeaders();
    // ...
}

您可以将 HTTPS 作为方案添加到您的 swagger UI 中以解决此问题:https://swagger.io/docs/specification/2-0/api-host-and-base-path/