swagger 屏蔽默认自带的接口和具体API?

1、SwaggerConfig.cs 文件中添加 DocumentFilter

 public class SwaggerConfig
    {
        public static void Register()
        {
            var thisAssembly = typeof(SwaggerConfig).Assembly;
            //获取项目文件路径
            var baseDirectory = AppDomain.CurrentDomain.BaseDirectory + @"\bin\";
            var commentsFileName = Assembly.GetExecutingAssembly().GetName().Name + ".XML";

            var commentsFile = Path.Combine(baseDirectory, commentsFileName);
            GlobalConfiguration.Configuration
                .EnableSwagger(c =>
                    {

                        c.SingleApiVersion("v1", "LoanManagement.OpenApi.LianYiRong");
                        c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
                        c.IncludeXmlComments(commentsFile);
                        //增加DocumentFilter
                        c.DocumentFilter();//隐藏Swagger 自带API及隐藏具体Api


                    })
                .EnableSwaggerUi(c =>
                    {
                        //汉化Swagger
                        c.InjectJavaScript(Assembly.GetExecutingAssembly(), "LoanManagement.OpenApi.LianYiRong.SwaggerUI.Scripts.swagger.js");

                    });
        }
    }

 2、增加HiddenApiFilter.cs类

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public partial class HiddenApiAttribute : Attribute { }
    public class HiddenApiFilter:IDocumentFilter
    {
        public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
        {
            foreach (ApiDescription apiDescription in apiExplorer.ApiDescriptions)
            {
                var _key = "/" + apiDescription.RelativePath.TrimEnd('/');
                // 过滤 swagger 自带的接口
                if (_key.Contains("/api/Swagger") && swaggerDoc.paths.ContainsKey(_key))
                    swaggerDoc.paths.Remove(_key);

                //隐藏具体Api接口 需要在想隐藏的api 上面添加特性[HiddenApi]
                if (Enumerable.OfType(apiDescription.GetControllerAndActionAttributes()).Any())
                {
                    string key = "/" + apiDescription.RelativePath;
                    if (key.Contains("?"))
                    {
                        int idx = key.IndexOf("?", System.StringComparison.Ordinal);
                        key = key.Substring(0, idx);
                    }
                    swaggerDoc.paths.Remove(key);
                }
            }
        }
    }

 

你可能感兴趣的:(Swagger)