接口 Swagger 部分Web API的隐藏

背景

Swagger是目前最受欢迎的REST APIs文档生成工具,同时也是API的在线测试工具。功能强大谁用谁知道。我就不用在这里推广它了。今天要解决的问题是:如果让一些特定的API接口在Swagger中不显示,即从Swagger中过滤掉一些不想展示的接口?通常我们使用Swagger都是通过指定要扫描的包或者扫描具有某些注解的Controller,来生成API,那么如果这其中还想过滤掉一些特定API怎么做呢?

实现方法

1、添加特性,隐藏swagger接口特性标识

  /// <summary>
        ///
        /// </summary>
        /// <param name="swaggerDoc"></param>
        /// <param name="context"></param>
        public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
        {
            foreach (ApiDescription apiDescription in context.ApiDescriptions)
            {
                if (apiDescription.TryGetMethodInfo(out MethodInfo method))
                {
                    if (method.ReflectedType.CustomAttributes.Any(t => t.AttributeType == typeof(HiddenApiAttribute))
                            || method.CustomAttributes.Any(t => t.AttributeType == typeof(HiddenApiAttribute)))
                    {
                        string key = "/" + apiDescription.RelativePath;
                        if (key.Contains("?"))
                        {
                            int idx = key.IndexOf("?", System.StringComparison.Ordinal);
                            key = key.Substring(0, idx);
                        }
                        swaggerDoc.Paths.Remove(key);
                    }
                }
            }
        }
    }

2、添加过滤器,自定义Swagger隐藏过滤器

 /// <summary>
    /// 隐藏swagger接口特性标识
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public class HiddenApiAttribute : System.Attribute
    {
    }

3、修改SwaggerConfig,注入过滤器

            #region Swagger

            services.AddSwaggerGen(c =>
          {
              c.SwaggerDoc("v1", new Info
              {
                  Version = "v1",
                  Title = "接口文档",
                  Description = "接口文档-基础",
                  TermsOfService = "https://example.com/terms",
                  Contact = new Contact
                  {
                      Name = "XXX1111",
                      Email = "XXX1111@qq.com",
                      Url = "https://example.com/terms"
                  }
                  ,
                  License = new License
                  {
                      Name = "Use under LICX",
                      Url = "https://example.com/license",
                  }
              });

              c.SwaggerDoc("v2", new Info
              {
                  Version = "v2",
                  Title = "接口文档",
                  Description = "接口文档-基础",
                  TermsOfService = "https://example.com/terms",
                  Contact = new Contact
                  {
                      Name = "XXX2222",
                      Email = "XXX2222@qq.com",
                      Url = "https://example.com/terms"
                  }
                   ,
                  License = new License
                  {
                      Name = "Use under LICX",
                      Url = "https://example.com/license",
                  }
              });
              c.OperationFilter<HttpHeaderOperationFilter>();
              c.DocumentFilter<HiddenApiFilter>();
              var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
              var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
              c.IncludeXmlComments(xmlPath);
              c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"CompanyName.ProjectName.ICommonServer.xml"));
          });

            #endregion Swagger

测试

 /////// <summary>
        /////// 检测帐号是不已存在
        /////// </summary>
        /////// <param name="account">(必填)帐号或手机号    Data=true 已存在,Data=false 不存在</param>
        /////// <returns>测试</returns>
        ////[HttpGet, Route("existAccount")]
        ////[ApiExplorerSettings(GroupName = "v2")]
        //////[HiddenApi]
        ////public R<bool> ExistAccount([FromQuery] string account)
        ////{
        ////    return R<bool>.Suc(true);
        ////}

开源地址

https://github.com/conanl5566/Sampleproject/tree/master/src/03%20Host/CompanyName.ProjectName.HttpApi.Host

 

posted @ 2021-01-06 13:43  UP技术控  阅读(326)  评论(0编辑  收藏