I tried StackOverflow, but got no answers, so I'll try here.
In v4, I could set the basePath as follows:
app.UseSwagger(c => {
c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.BasePath = "/folder/data");
});
In v5, all the classes pertaining to this changed and I am unclear how to replicate the code above. I tried the following, but just don't see where exactly to set the BasePath:
app.UseSwagger(c => {
c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
{
var paths = new OpenApiPaths();
var pathItem = new OpenApiPathItem();
paths.Add("main", pathItem);
swaggerDoc.Paths = paths;
});
});
So how does one set a BasePath?
BasePath was used in Swagger v2.0: https://swagger.io/docs/specification/2-0/api-host-and-base-path/
It has been replaced by the servers array in OpenApi v3.0: https://swagger.io/docs/specification/api-host-and-base-path/
In v5 you have to do this for using OpenAapi v3.0:
var basePath = "/v1";
app.UseSwagger(c =>
{
c.RouteTemplate = "swagger/{documentName}/swagger.json";
c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
{
swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}{basePath}" } };
});
});
but you won't get a basePath property in the json file.
Or this for using Swagger v2.0:
var basePath = "/v1";
app.UseSwagger(c =>
{
c.SerializeAsV2 = true;
c.RouteTemplate = "swagger/{documentName}/swagger.json";
c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
{
swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}{basePath}" } };
});
});
And then your basePath will be /v1
I came up with a similar solution, using DocumentFilter:
public class SwaggerDocumentFilter : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
swaggerDoc.Servers.Add(new OpenApiServer() { Url = "/basepath" });
}
}
and in Startup.cs:
services.AddSwaggerGen(options =>
{
options.DocumentFilter<SwaggerDocumentFilter>();
});
None of these wroked for me. I need to be able to set relative basePath witout setting hostbalue or httpReg scheme. Only setting a relative basePath. Have asked the question here https://stackoverflow.com/questions/61733433/how-do-i-setup-swashbucle-v5-with-swagger-when-i-have-a-custom-base-url
Most helpful comment
BasePathwas used in Swagger v2.0: https://swagger.io/docs/specification/2-0/api-host-and-base-path/It has been replaced by the
serversarray in OpenApi v3.0: https://swagger.io/docs/specification/api-host-and-base-path/In v5 you have to do this for using OpenAapi v3.0:
but you won't get a basePath property in the json file.
Or this for using Swagger v2.0:
And then your basePath will be
/v1