Asp.Net Core 2.x 和 3.x WebAPI 使用 Swagger 時 API Controller 控制器 Action 方法 隱藏 hidden 與 and 分組 group

一、前言

爲何咱們要隱藏部分接口?前端

由於咱們在用swagger代替接口的時候,不免有些接口會直觀的暴露出來,好比咱們結合Consul一塊兒使用的時候,會將健康檢查接口以及報警通知接口暴露出來,這些接口有時候會出於方便考慮,沒有進行加密,這個時候咱們就須要把接口隱藏起來,只有內部的開發者知道。json

爲何要分組?後端

一般當咱們寫先後端分離的項目的時候,不免會遇到編寫不少接口供前端頁面進行調用,當接口達到幾百個的時候就須要區分哪些是框架接口,哪些是業務接口,這時候給swaggerUI的接口分組是個不錯的選擇。api

 

swagger的基本使用這裏將再也不贅述,能夠閱讀微軟官方文檔,便可基本使用app

二、swaggerUI中加入受權請求

  • 新建 HttpHeaderOperationFilter 操做過濾器,繼承 Swashbuckle.AspNetCore.SwaggerGen.IOperationFilter 接口,實現 Apply 方法
    複製代碼
    /// <summary>
    /// swagger請求頭
    /// </summary>
    public class HttpHeaderOperationFilter : IOperationFilter
    {
        public void Apply(Operation operation, OperationFilterContext context)
        {
            #region 新方法
            if (operation.Parameters == null)
            {
                operation.Parameters = new List<IParameter>();
            }
    
            if (context.ApiDescription.TryGetMethodInfo(out MethodInfo methodInfo))
            {
                if (!methodInfo.CustomAttributes.Any(t => t.AttributeType == typeof(AllowAnonymousAttribute))
                        &&!(methodInfo.ReflectedType.CustomAttributes.Any(t => t.AttributeType == typeof(AuthorizeAttribute))))
                {
                    operation.Parameters.Add(new NonBodyParameter
                    {
                        Name = "Authorization",
                        In = "header",
                        Type = "string",
                        Required = true,
                        Description = "請輸入Token,格式爲bearer XXX"
                    });
                }
            }
            #endregion
    
            #region 已過期
            //if (operation.Parameters == null)
            //{
            //    operation.Parameters = new List<IParameter>();
            //}
            //var actionAttrs = context.ApiDescription.ActionAttributes().ToList();
            //var isAuthorized = actionAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute));
            //if (isAuthorized == false)
            //{
            //    var controllerAttrs = context.ApiDescription.ControllerAttributes();
            //    isAuthorized = controllerAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute));
            //}
            //var isAllowAnonymous = actionAttrs.Any(a => a.GetType() == typeof(AllowAnonymousAttribute));
            //if (isAuthorized && isAllowAnonymous == false)
            //{
            //    operation.Parameters.Add(new NonBodyParameter
            //    {
            //        Name = "Authorization",
            //        In = "header",
            //        Type = "string",
            //        Required = true,
            //        Description = "請輸入Token,格式爲bearer XXX"
            //    });
            //}
            #endregion
        }
    }
    複製代碼
  • 而後修改 Startup.cs 中的 ConfigureServices 方法,添加咱們自定義的 HttpHeaderOperationFilter 過濾器
    複製代碼
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddSwaggerGen(c =>
        {
            ...
            c.OperationFilter<HttpHeaderOperationFilter>();
        });
        ...
    }
    複製代碼

    這時候咱們再訪問swaggerUI就能夠輸入Token了
    框架

三、API分組

  • 修改 Startup.cs 中的 ConfigureServices 方法,添加多個swagger文檔
    複製代碼
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info
            {
                Version = "v1",
                Title = "接口文檔",
                Description =  "接口文檔-基礎",
                TermsOfService = "",
                Contact = new Contact
                {
                    Name = "XXX1111",
                    Email = "XXX1111@qq.com",
                    Url = ""
                }
            });
    
            c.SwaggerDoc("v2", new Info
            {
                Version = "v2",
                Title = "接口文檔",
                Description =  "接口文檔-基礎",
                TermsOfService = "",
                Contact = new Contact
                {
                    Name = "XXX2222",
                    Email = "XXX2222@qq.com",
                    Url = ""
                }
            });
    
            //反射注入所有程序集說明
            GetAllAssemblies().Where(t => t.CodeBase.EndsWith("Controller.dll")).ToList().ForEach(assembly =>
                {
                    c.IncludeXmlComments(assembly.CodeBase.Replace(".dll", ".xml"));
                });
    
            c.OperationFilter<HttpHeaderOperationFilter>();
            //c.DocumentFilter<HiddenApiFilter>();
        });
        ...
    }
    複製代碼
  • 修改 Startup.cs 中的 Configure 方法,加入
    複製代碼
    public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
    {
        ...
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v2/swagger.json", "接口文檔-基礎");//業務接口文檔首先顯示
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "接口文檔-業務");//基礎接口文檔放後面後顯示
            c.RoutePrefix = string.Empty;//設置後直接輸入IP就能夠進入接口文檔
        });
        ...
    
    }
    複製代碼

     

  • 而後還要在咱們的控制器上面標註swagger文檔的版本
    前後端分離

    這時候咱們就能夠將接口文檔進行分組顯示了
    ide

四、API隱藏

    • 建立自定義隱藏特性 HiddenApiAttribute.cs 
      複製代碼
      /// <summary>
      /// 隱藏swagger接口特性標識
      /// </summary>
      [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
      public class HiddenApiAttribute:System.Attribute
      {
      }
      複製代碼
    • 建立API隱藏過濾器 HiddenApiFilter 繼承 Swashbuckle.AspNetCore.SwaggerGen.IDocumentFilter 接口,實現 Apply 方法
      複製代碼
      /// <summary>
      /// 自定義Swagger隱藏過濾器
      /// </summary>
      public class HiddenApiFilter : IDocumentFilter
      {
          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);
                      }
                  }
              }
          }
      }
      複製代碼
    • 在 Startup.cs 中使用 HiddenApiFilter 
      複製代碼
      public IServiceProvider ConfigureServices(IServiceCollection services)
      {
          ...
          services.AddSwaggerGen(c =>
          {
              c.SwaggerDoc("v1", new Info
              {
                  Version = "v1",
                  Title = "接口文檔",
                  Description =  "接口文檔-基礎",
                  TermsOfService = "",
                  Contact = new Contact
                  {
                      Name = "XXX1111",
                      Email = "XXX1111@qq.com",
                      Url = ""
                  }
              });
      
              c.SwaggerDoc("v2", new Info
              {
                  Version = "v2",
                  Title = "接口文檔",
                  Description =  "接口文檔-基礎",
                  TermsOfService = "",
                  Contact = new Contact
                  {
                      Name = "XXX2222",
                      Email = "XXX2222@qq.com",
                      Url = ""
                  }
              });
      
              //反射注入所有程序集說明
              GetAllAssemblies().Where(t => t.CodeBase.EndsWith("Controller.dll")
                  && !t.CodeBase.Contains("Common.Controller.dll")).ToList().ForEach(assembly =>
                  {
                      c.IncludeXmlComments(assembly.CodeBase.Replace(".dll", ".xml"));
                  });
      
              c.OperationFilter<HttpHeaderOperationFilter>();
              c.DocumentFilter<HiddenApiFilter>();
          });
          ...
      }
      複製代碼
    • 示例:
      我這裏提供了Consul的心跳檢車接口

      可是在接口文檔中並無顯示出來
      visual-studio

相關文章
相關標籤/搜索