All Downloads are FREE. Search and download functionalities are using the official Maven repository.

aspnetcore.2.0.Filters.BasePathFilter.mustache Maven / Gradle / Ivy

There is a newer version: 7.6.0
Show newest version
using System.Linq;
using System.Text.RegularExpressions;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace {{packageName}}.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
        /// 
        /// SwaggerDocument
        /// FilterContext
        public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
        {
            swaggerDoc.BasePath = BasePath;

            var pathsToModify = swaggerDoc.Paths.Where(p => p.Key.StartsWith(BasePath)).ToList();

            foreach (var path in pathsToModify)
            {
                if (path.Key.StartsWith(BasePath))
                {
                    string newKey = Regex.Replace(path.Key, $"^{BasePath}", string.Empty);
                    swaggerDoc.Paths.Remove(path.Key);
                    swaggerDoc.Paths.Add(newKey, path.Value);
                }
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy