Asp.Net Core 2.x and 3.x WebAPI use Swagger API Controller Controller Action method hidden and hidden packet group and

1 Introduction

Why do we have to hide part of the interface?

Because when we replace the interface with a swagger, inevitably some intuitive interfaces will be exposed, such as when we combined use with the Consul, health checks will alarm interface and notification interface exposed, these interfaces sometimes for convenience, not encrypted, this time we need to interface to hide, only internal developers know.

Why Packet?

Usually when we write separate front and rear end of the project, you will inevitably encounter a lot of writing an interface for the front page is called when the interface reaches a few hundred when you need to understand which are the framework of the interface, which is a service interface, this time for swaggerUI Interface grouping is a good choice.

 

The basic use of swagger will not repeat them here, you can read Microsoft's official documentation , you can basically use

2, swaggerUI authorization request was added

  • New  HttpHeaderOperationFilter operation of the filter, inherited  Swashbuckle.AspNetCore.SwaggerGen.IOperationFilter interface,  the Apply method
    Copy the code
    /// <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
            //} 
        } 
    }
    Copy the code
  • Then modify  Startup.cs in  ConfigureServices method, add our custom  HttpHeaderOperationFilter filter
    Copy the code
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddSwaggerGen(c =>
        {
            ...
            c.OperationFilter<HttpHeaderOperationFilter>();
        });
        ...
    }
    Copy the code

    This time we'll visit swaggerUI can enter the Token

3, API group

  • Modify  Startup.cs in  ConfigureServices method, add more swagger documents
    Copy the code
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info
            {
                Version = "v1",
                Title = "接口文档",
                Description =  "接口文档-基础",
                TermsOfService = "",
                Contact = new Contact
                {
                    Name = "XXX1111",
                    Email = "[email protected]",
                    Url = ""
                }
            });
    
            c.SwaggerDoc("v2", new Info
            {
                = Version " v2 ", 
                the Title = "interface documentation", 
                the Description = "Document Interface - Basic", 
                termsOfService = "", 
                Business Card = new new Business Card 
                { 
                    the Name = "XXX2222", 
                    Email = "[email protected]", 
                    the Url = "" 
                } 
            }); 
    
            // reflective injection all assemblies described 
            GetAllAssemblies () the Where (T => t.CodeBase.EndsWith (. "Controller.dll")) ToList () the ForEach (assembly =>.. 
                { 
                    c.IncludeXmlComments (assembly.CodeBase.Replace ( "DLL.", ".xml")); 
                });
    
            c.OperationFilter<HttpHeaderOperationFilter>();
            //c.DocumentFilter<HiddenApiFilter>();
        });
        ...
    }
    Copy the code
  • Modified  Startup.cs the  Configure method, was added
    Copy the code
    void the Configure public (App IApplicationBuilder, ILoggerFactory LoggerFactory) 
    { 
        ... 
        app.UseSwagger (); 
        app.UseSwaggerUI (C => 
        { 
            c.SwaggerEndpoint ( "/ Swagger / V2 /swagger.json", "Document Interface - Basic") ; // service interface document displayed first 
            c.SwaggerEndpoint ( "/ Swagger / v1 /swagger.json", "interface documentation - business"); // show the basic interface documentation put behind 
            c.RoutePrefix = string.Empty; // after setting input directly into the interface document can be IP 
        }); 
        ... 
    
    }
    Copy the code

     

  • And then also the top mark in our controller version swagger document

    This time we will be able to interface documentation to group shows

4, API hidden

    • Create a custom hidden characteristics  HiddenApiAttribute.cs 
      Copy the code
      /// <summary>
      /// 隐藏swagger接口特性标识
      /// </summary>
      [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
      public class HiddenApiAttribute:System.Attribute
      {
      }
      Copy the code
    • Creating API Hide Filters  HiddenApiFilter inherited  Swashbuckle.AspNetCore.SwaggerGen.IDocumentFilter interface,  Apply method
      Copy the code
      /// <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);
                      }
                  }
              }
          }
      }
      Copy the code
    • In  use Startup.cs in  HiddenApiFilter 
      Copy the code
      public IServiceProvider ConfigureServices(IServiceCollection services)
      {
          ...
          services.AddSwaggerGen(c =>
          {
              c.SwaggerDoc("v1", new Info
              {
                  Version = "v1",
                  Title = "接口文档",
                  Description =  "接口文档-基础",
                  TermsOfService = "",
                  Contact = new Contact
                  {
                      Name = "XXX1111",
                      Email = "[email protected]",
                      Url = ""
                  }
              });
      
              c.SwaggerDoc("v2",Info new new 
                  the Title = "interface documentation"
                  Version = "v2",
              {
                  Description =  "接口文档-基础",
                  TermsOfService = "",
                  Contact = new Contact
                  {
                      Name = "XXX2222",
                      Email = "[email protected]",
                      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>();
          });
          ...
      }
      Copy the code
    • Example:
      I am here to provide Consul heartbeat interfaces inspection car

      But it did not show up in the interface document

       

Guess you like

Origin www.cnblogs.com/webenh/p/11605718.html