aspnetcore.3.0.Filters.BasePathFilter.mustache Maven / Gradle / Ivy
{{>partial_header}}
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace {{packageName}}.Filters
{
///
/// BasePath Document Filter sets BasePath property of OpenAPI 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 OpenAPI Doc
///
/// The BasePath of the OpenAPI Doc
public string BasePath { get; }
///
/// Apply the filter
///
/// OpenApiDocument
/// FilterContext
public void Apply(OpenApiDocument openapiDoc, DocumentFilterContext context)
{
//openapiDoc.BasePath = BasePath;
var pathsToModify = openapiDoc.Paths.Where(p => p.Key.StartsWith(BasePath)).ToList();
foreach (var (key, value) in pathsToModify)
{
if (key.StartsWith(BasePath))
{
var newKey = Regex.Replace(key, $"^{BasePath}", string.Empty);
openapiDoc.Paths.Remove(key);
openapiDoc.Paths.Add(newKey, value);
}
}
}
}
}