如何在 Swashbuckle for .NET Core 中指定 https 方案

How to specify https scheme in Swashbuckle for .NET Core

如何在 .NET Core 版本的 Swashbuckle 中指定 https 架构?在 ASP.NET 版本中我可以做到

.EnableSwagger(c =>
{
  c.Schemes(new[] { "https" });
}

但我在 AddSwaggerGen 中没有看到任何类似的东西。

只需实现接口 IDocumentFilter 并在 Startup.cs 中使用它:

public class TestFilter : IDocumentFilter
{
    public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
    {
        swaggerDoc.Schemes = new string[] { "http" };
    }
}

// Startup.cs
services.AddSwaggerGen(c =>
{
     c.SwaggerDoc("v2", new Swashbuckle.AspNetCore.Swagger.Info 
                        { Title = "My API", Version = "v2" });
     c.DocumentFilter<TestFilter>();
 });

您可以在 swagger 最新版本中使用此代码:

 public class SwaggerDocumentFilter : IDocumentFilter

    {

        private readonly string _swaggerDocHost;


        public SwaggerDocumentFilter(IHttpContextAccessor httpContextAccessor)

        {

            var host = httpContextAccessor.HttpContext.Request.Host.Value;

            var scheme = httpContextAccessor.HttpContext.Request.Scheme;

            _swaggerDocHost = $"{scheme}://{host}";

        }


        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)

        {

            swaggerDoc.Servers.Add(new OpenApiServer { Url = _swaggerDocHost });

        }

    }

如果要设置_swaggerDocHost="https://sitename".

在 Swashbuckle.AspNetCore v 6.0.7 中,您可以这样做:

                app.UseSwagger(c => {
                    c.PreSerializeFilters.Add((swagger, httpReq) =>
                    {
                        swagger.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"https://{httpReq.Host.Host}" } };
                    });
                });

请注意:以上示例假定端口为 443,如果不是这样,您还必须提供您的 https 端口号。

@marius 的解决方案对我有用,但在本地启动时除外。正如他正确指出的那样 httpReq.Host.Host 将省略端口号。作为一项改进,下面的代码片段保留了端口号并且在本地主机和托管 API 上都有效。 注意:我的本地主机在 HTTP

Nuget 包版本:Swashbuckle.AspNetCore6.0.7

app.UseSwagger(options =>
{
    options.PreSerializeFilters.Add((swagger, httpReq) =>
    {
        var scheme = httpReq.Host.Host.StartsWith("localhost", StringComparison.OrdinalIgnoreCase) ? "http" : "https";
        swagger.Servers = new List<OpenApiServer>() {new OpenApiServer() {Url = $"{scheme}://{httpReq.Host}"}};
    });
});