Swashbuckle.WebApi
Swashbuckle.WebApi copied to clipboard
Changing RelativePath reflects only after 2 page loads
VERSION:
Swashbuckle.AspNetCore v6.1.5 in an Asp.Net Core 5 project.
STEPS TO REPRODUCE:
Add this Route Filter
// This filter has been simplified for debugging purposes.
public class SwaggerRouteFilter : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
// This will update the first action endpoint path found.
foreach (var apiDescription in context.ApiDescriptions)
{
apiDescription.RelativePath = "overwritten/path";
break;
}
}
}
Add this to your startup.cs
services.AddSwaggerGen(c =>
{
c.DocumentFilter<SwaggerRouteFilter>();
}
Test procedure
- Load your swagger UI or Json file. Notice that your first endpoint's relative-path has not changed. Its still the same.
- Refresh your browser. Notice that only now the relative-path has changed.
EXPECTED RESULT:
On the first page load, the relative path of the first endpoint should change.
ACTUAL RESULT:
The relative path only changes on the second loading of the page.
ADDITIONAL DETAILS
A similar issue https://github.com/domaindrivendev/Swashbuckle.WebApi/issues/361 was reported in 2015 but instead of using a IDocumentFilter it was using IOperationFilter.
@krugertech as was mentioned on the earlier issue you found, the ApiDescription is just passed for context - what you need to be modifying in an IDocumentFilter is the OpenApiDocument parameter. In the above-described case you could do something like:
public class SwaggerRouteFilter : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
var firstPath = string.Empty;
var firstEndpoint = null;
foreach (var path in swaggerDoc.Paths)
{
firstPath = path.Key; // the path
firstEndpoint = path.Value; // the OpenApiPathItem representing the operations/parameters/etc
break;
}
swaggerDoc.Paths.Remove(firstPath);
swaggerDoc.Paths.Add("overwritten/path", firstEndpoint);
}
}
It seems like root cause of the behaviour you saw is that the ApiDescription gets cached internally, so when you modify it during one page load, the change happens to be reflected on subsequent page loads.
I'm assuming by now (a year+ after raising the issue) you have either found a solution or moved on - but hopefully this can help others who run into the same thing, like I did 😁