阅读 122

接口 Swagger 部分Web API的隐藏

背景

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

实现方法

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

  /// 
        ///
        /// 
        /// 
        /// 
        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隐藏过滤器

 /// 
    /// 隐藏swagger接口特性标识
    /// 
    [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();
              c.DocumentFilter();
              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

测试

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

开源地址

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

 

原文:https://www.cnblogs.com/lyl6796910/p/14240601.html

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐