How can I specify https
schema in the .NET Core
version of Swashbuckle? In ASP.NET version I could do
.EnableSwagger(c =>
{
c.Schemes(new[] { "https" });
}
but I don't see anything similar as part of AddSwaggerGen.
How can I specify https
schema in the .NET Core
version of Swashbuckle? In ASP.NET version I could do
.EnableSwagger(c =>
{
c.Schemes(new[] { "https" });
}
but I don't see anything similar as part of AddSwaggerGen.
Just implement the interface IDocumentFilter
and use it in 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>();
});
The solution from @marius worked for me, except when launched locally. As he rightly points out that httpReq.Host.Host will omit port number. As an improvement, the snippet below keeps the port number and works both on localhost as well as hosted API. NOTE: my localhost is on HTTP
Nuget Package version: 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}"}};
});
});
In Swashbuckle.AspNetCore v 6.0.7 you can do this:
app.UseSwagger(c => {
c.PreSerializeFilters.Add((swagger, httpReq) =>
{
swagger.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"https://{httpReq.Host.Host}" } };
});
});
Please note: the above example assumes port 443, you will have to provide your https port number as well if this is not the case.
You can use this code at swagger latest version:
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 });
}
}
If you want to set _swaggerDocHost="https://sitename".