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<HiddenApiFilter>();//隱藏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<HiddenApiAttribute>(apiDescription.GetControllerAndActionAttributes<HiddenApiAttribute>()).Any())
                {
                    string key = "/" + apiDescription.RelativePath;
                    if (key.Contains("?"))
                    {
                        int idx = key.IndexOf("?", System.StringComparison.Ordinal);
                        key = key.Substring(0, idx);
                    }
                    swaggerDoc.paths.Remove(key);
                }
            }
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章