Asp.Net Core WebAPI使用Swagger时API隐藏和分组详解

所属分类: 网络编程 / ASP.NET 阅读数: 1611
收藏 0 赞 0 分享

1、前言

为什么我们要隐藏部分接口?

因为我们在用swagger代替接口的时候,难免有些接口会直观的暴露出来,比如我们结合Consul一起使用的时候,会将健康检查接口以及报警通知接口暴露出来,这些接口有时候会出于方便考虑,没有进行加密,这个时候我们就需要把接口隐藏起来,只有内部的开发者知道。

为什么要分组?

通常当我们写前后端分离的项目的时候,难免会遇到编写很多接口供前端页面进行调用,当接口达到几百个的时候就需要区分哪些是框架接口,哪些是业务接口,这时候给swaggerUI的接口分组是个不错的选择。

swagger的基本使用这里将不再赘述,可以阅读微软官方文档,即可基本使用

2、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了

3、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文档的版本

这时候我们就可以将接口文档进行分组显示了

4、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的心跳检车接口

但是在接口文档中并没有显示出来

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。

更多精彩内容其他人还在看

解析WPF实现音频文件循环顺序播放的解决方法

本篇文章是对WPF实现音频文件循环顺序播放的方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

解决.net framework 4.0环境下遇到版本不同编译不通过的方法详解

本篇文章是对.net framework 4.0环境下遇到版本不同编译不通过的解决方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

将文件上传、下载(以二进制流保存到数据库)实现代码

将文件以二进制流的格式写入数据库:首先获得文件路径,然后将文件以二进制读出保存在一个二进制数组中具体请祥看本文,希望对你有所帮助
收藏 0 赞 0 分享

点击提交按钮后DropDownList的值变为默认值实现分析

在点击提交按钮后,页面上所有的绑定到数据库的控件值都恢复到默认值,下面与大家分享下DropDownList的值变为默认值
收藏 0 赞 0 分享

ASP.NET web.config中数据库连接字符串connectionStrings节的配置方法

ASP.NET web.config中数据库连接字符串connectionStrings节的配置方法,需要的朋友可以参考一下
收藏 0 赞 0 分享

Linkbutton控件在项目中的简单应用

Button控件可分为button控件、LinkButton控件、ImageButton控件三类,而LinkButton控件则在页面上显示为一个超级链接,下面与大家分享下其具体应用
收藏 0 赞 0 分享

Web.config 和 App.config 的区别分析

Web.config 和 App.config 的区别分析,需要的朋友可以参考一下
收藏 0 赞 0 分享

基于.Net中的数字与日期格式化规则助记词的使用详解

本篇文章是对.Net中的数字与日期格式化规则助记词的使用进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

解决在Web.config或App.config中添加自定义配置的方法详解

本篇文章是对在Web.config或App.config中添加自定义配置的方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

深入本机影像生成器(Ngen.exe)工具使用方法详解

本篇文章是对本机影像生成器(Ngen.exe)工具使用方法进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享
查看更多