欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-20 21:06:16
1、前言 为什么我们要隐藏部分接口? 因为我们在用swagger代替接口的时候,难免有些接口会直观的暴露出来,比如我们结合consul一起使用的时候,会将健康检查接口以...

1、前言

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

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

为什么要分组?

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

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

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了

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

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

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

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

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

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

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

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

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

总结

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