using System.Linq; using System.Text.RegularExpressions; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; using Microsoft.OpenApi.Models; namespace IO.Swagger.Filters { /// /// BasePath Document Filter sets BasePath property of Swagger and removes it from the individual URL paths /// public class BasePathFilter : IDocumentFilter { /// /// Constructor /// /// BasePath to remove from Operations public BasePathFilter(string basePath) { BasePath = basePath; } /// /// Gets the BasePath of the Swagger Doc /// /// The BasePath of the Swagger Doc public string BasePath { get; } /// /// Apply the filter /// /// OpenApiDocument /// FilterContext public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { swaggerDoc.Servers.Add(new OpenApiServer() { Url = this.BasePath }); var pathsToModify = swaggerDoc.Paths.Where(p => p.Key.StartsWith(this.BasePath)).ToList(); foreach (var path in pathsToModify) { if (path.Key.StartsWith(this.BasePath)) { string newKey = Regex.Replace(path.Key, $"^{this.BasePath}", string.Empty); swaggerDoc.Paths.Remove(path.Key); swaggerDoc.Paths.Add(newKey, path.Value); } } } } }