【发布时间】:2021-03-04 07:38:09
【问题描述】:
如何在 Swashbuckle 的 .NET Core 版本中指定 https 架构?在 ASP.NET 版本中我可以做到
.EnableSwagger(c =>
{
c.Schemes(new[] { "https" });
}
但我没有看到任何与 AddSwaggerGen 类似的东西。
【问题讨论】:
标签: swagger swashbuckle
如何在 Swashbuckle 的 .NET Core 版本中指定 https 架构?在 ASP.NET 版本中我可以做到
.EnableSwagger(c =>
{
c.Schemes(new[] { "https" });
}
但我没有看到任何与 AddSwaggerGen 类似的东西。
【问题讨论】:
标签: swagger swashbuckle
只需实现接口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>();
});
【讨论】:
swaggerDoc.Schemes 无法解析。
@marius 的解决方案对我有用,除非在本地启动。正如他正确指出的那样, httpReq.Host.Host 将省略端口号。作为一项改进,下面的 sn-p 保留了端口号,并且可以在 localhost 和托管 API 上运行。 注意:我的本地主机在 HTTP 上
Nuget 包版本:Swashbuckle.AspNetCore 6.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}"}};
});
});
【讨论】:
在 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 端口号。
【讨论】:
using Microsoft.OpenApi.Models;。在那些花括号/面括号之后,换行符也不会伤害一些空白:wink:.
您可以在 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"。
【讨论】: