I have a .NET Core Web API with versioning in place. There are 2 versions currently, and the operation paths in the 2 swagger files look something like:
/api/v1/Versioning/List (v1 swagger)
/api/v2/Versioning/List (v2 swagger)
There is a build pipeline in Azure DevOps that generates the 2 swagger files using PowerShell:
`dotnet swagger tofile --output pathToV1Json MyApplication.dll v1`
and
`dotnet swagger tofile --output pathToV2Json MyApplication.dll v2`
and stores them in the artifact. In the release pipeline, I'm using the Create or Update Versioned API
API Management task to create/update my API in Azure API Management, using those generated swagger files.
So far so good, everything works as expected. But, the release step adds another version part to the URL, as is to be expected. So in my final API operations in API Management, the URL's look something like this:
.../v1/api/v1/Versioning/List (v1 swagger)
.../v2/api/v2/Versioning/List (v2 swagger)
I was trying to edit the generated operation paths in the swagger files by using an IDocumentFilter and that works, but it also breaks the Swagger UI. Is there some way that I can modify those operation paths, but only when generating the actual Swagger file?
So in my IDocumentFilter, I could have something like this:
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
var openApiPaths = new OpenApiPaths();
foreach (var path in swaggerDoc.Paths)
{
if ([generating actual swagger file])
{
openApiPaths.Add(path.Key.Replace("/v1", ""), path.Value);
}
else
{
openApiPaths.Add(path.Key, path.Value);
}
}
swaggerDoc.Paths = openApiPaths;
}
You can inject an IHttpContextAccessor into your DocumentFilter, and check whether there actually is an HttpRequest available, like so:
public class DocumentFilter : IDocumentFilter
{
private readonly IHttpContextAccessor _httpContextAccessor;
public DocumentFilter(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
var request = _httpContextAccessor.HttpContext?.Request;
if (request == null)
{
var copy = new OpenApiPaths();
foreach (var path in swaggerDoc.Paths)
{
var newKey = path.Key.Replace("x", "y");
copy.Add(newKey, path.Value);
}
swaggerDoc.Paths.Clear();
swaggerDoc.Paths = copy;
}
}
}