I have multiple web api projects (microservices), and I want to expose them using only one swagger-ui link. I'll call each web api project EndpointA and EndpointB for the sake of this post.
I've created a swagger-ui project, and I've added each endpoint to this project.
My swagger-ui project Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/EndpointA/swagger/v1/swagger.json", "EndpointA");
c.SwaggerEndpoint("/EndpointB/swagger/v1/swagger.json", "EndpointB");
});
}
My endpoints A/B Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "EndpointA", // or "EndpointB",
});
});
}
My problem is that each of the swagger.json
files doesn't contains the endpoint prefix. Instead of being /EndpointA/Controller/Action
, the paths are /Controller/Action
, which are not valid.
I have tried to set a custom url prefix in my swagger ui project like this c.RoutePrefix = "EndpointA";
. It works for my EndpointA, but I can only set one for all endpoints so EndpointB won't works.
I also tried to set a prefix directly in each endpoint using SwaggerGen
, but I don't know how / if it's possible.
Look for the following code: url: "http://petstore.swagger.io/v2/swagger.json", Change the url value from http://petstore.swagger.io/v2/swagger.json to a relative path to your YAML file, and then save the file.
By default, Swagger UI uses BaseLayout , which is built into the application. You can specify a different layout to be used by passing the layout's name as the layout parameter to Swagger UI. Be sure to provide your custom layout as a component to Swagger UI.
By default, Swagger UI is accessible at /q/swagger-ui .
I ended up using the UsePathBaseExtensions.UsePathBase(IApplicationBuilder, PathString)
Method to register a base path to my api.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UsePathBase(new PathString("/EndpointA"));
app.UseMvc();
}
An alternate solution would have been to use the swagger base path document filter like so:
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.DocumentFilter<BasePathFilter>();
});
}
And the filter:
public class BasePathFilter: IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
swaggerDoc.BasePath = "/EndpointA";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With