asp.net core web api 生成 swagger 文档

Intro

在前后端分离的开发模式下,文档就显得比较重要,哪个接口要传哪些参数,如果一两个接口还好,口头上直接沟通好就可以了,如果接口多了就有点不适用了,没有接口文档会大大提高前后端的沟通成本。而 asp.net core 可以通过 Swashbuckle.AspNetCore 很方便的集成 swagger 文档,相比之下 nodejs(express) 和 swagger 集成就很麻烦了,大概这就是强类型语言的优势吧。C# 是最好的编程语言~~~

集成 swagger

  1. 配置 model 以及 api 项目生成 xml 文档

    在对应项目的项目文件中加入下面的代码,配置生成 xml 文档

      <PropertyGroup>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
    <NoWarn>$(NoWarn);1591</NoWarn>
    </PropertyGroup>
  2. 在 Web 项目上引用 Swashbuckle.AspNetCore

  3. 配置 web 项目使用 swagger

    1. 配置 ConfigureServices,配置示例代码

      services.AddSwaggerGen(options =>
      {
      options.SwaggerDoc(ApplicationHelper.ApplicationName, new Info { Title = "活动室预约系统 API", Version = "1.0" }); options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{typeof(Notice).Assembly.GetName().Name}.xml")); //使用Model项目的xml文档
      options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{typeof(NoticeController).Assembly.GetName().Name}.xml"), true); //使用ApiController项目的xml文档
      });
    2. 配置 Configure ,配置示例代码

      app
      .UseSwagger()
      .UseSwaggerUI(c =>
      {
      // c.RoutePrefix = string.Empty; //配置swagger ui前缀,默认值是 "swagger",你可以使用 "string.Empty"来配置首页就是 swagger ui
      c.SwaggerEndpoint($"/swagger/{ApplicationHelper.ApplicationName}/swagger.json", "活动室预约系统 API");
      c.DocumentTitle = "活动室预约系统 API";
      });
    3. 现在重新启动项目,访问 "/swagger" 就可以看到效果了

其他小技巧

  1. 忽略某些api,可以在controller 上加Attribute[ApiExplorerSettings(IgnoreApi = true)],这个Attribute 支持继承,也就是说你可以在一个BaseController 上加这个 Attribute ,这样继承于这个 BaseController 的 Controller 的接口都不会显示在 swagger 文档中

  2. 添加自定义请求头参数,可以自定义一个 OperationFilter

    1. 定义 OperationFilter 示例

      public class AuthorizationOperationFilter : IOperationFilter
      {
      public void Apply(Operation operation, OperationFilterContext context)
      {
      if (operation.Parameters == null)
      {
      operation.Parameters = new List<IParameter>();
      }
      var filterPipeline = context.ApiDescription.ActionDescriptor.FilterDescriptors;
      var isAuthorized = filterPipeline.Any(filter => filter.Filter is AuthorizeFilter);
      var allowAnonymous = filterPipeline.Any(filter => filter.Filter is IAllowAnonymousFilter); if (isAuthorized && !allowAnonymous)
      {
      operation.Parameters.Add(new NonBodyParameter()
      {
      Name = "Authorization",
      In = "header",
      Type = "string",
      Description = "access token",
      Required = true
      });
      }
      }
      } public class ApiVersionOperationFilter : IOperationFilter
      {
      public void Apply(Operation operation, OperationFilterContext context)
      {
      if (operation.Parameters == null)
      {
      operation.Parameters = new List<IParameter>();
      }
      context.ApiDescription.TryGetMethodInfo(out var methodInfo); if (methodInfo.DeclaringType.IsDefined(typeof(ApiVersionAttribute), true))
      {
      operation.Parameters.Add(new NonBodyParameter()
      {
      Name = "Api-Version",
      In = "header",
      Type = "string",
      Description = "Api-Version",
      Required = true,
      Default = "1.0"
      });
      }
      }
      }
    2. 配置 swagger 使用 OperationFilter

      services.AddSwaggerGen(options =>
      {
      // ...
      options.OperationFilter<AuthorizationOperationFilter>();
      });
    3. 直接配置使用全局Auth

       options.AddSecurityDefinition("Bearer", new ApiKeyScheme
      {
      Name = "Authorization",
      In = "header",
      Description = "Bearer token"
      });
      options.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
      {
      { "Bearer", Enumerable.Empty<string>() }
      });
  3. 更多技术及骚操作参考官方文档介绍 https://github.com/domaindrivendev/Swashbuckle.AspNetCore

示例

API 接口 swagger 文档 https://reservation.weihanli.xyz/swagger/index.html

这个API 接口文档只显示了API接口,服务器端其他的Controller 使用了上面提到的 [ApiExplorerSettings(IgnoreApi = true)] 忽略了

最近我的活动室预约的项目增加了一个前后端分离的 angular + marterial 的客户端,体验地址 https://reservation-client.weihanli.xyz/

Reference

asp.net core web api 生成 swagger 文档的更多相关文章

  1. asp.net core 2.1 生成swagger文档

    新建asp.netcore2.1 api项目 “WebApplication1” 在nuget管理器中添加对Swashbuckle.AspNetCore 3.0.0.Microsoft.AspNetC ...

  2. Asp.Net Core Web Api 使用 Swagger 生成 api 说明文档

    最近使用 Asp.Net Core Web Api 开发项目服务端.Swagger 是最受欢迎的 REST APIs 文档生成工具之一,进入我的视野.以下为学习应用情况的整理. 一.Swagger 介 ...

  3. 使用 Swagger 自动生成 ASP.NET Core Web API 的文档、在线帮助测试文档(ASP.NET Core Web API 自动生成文档)

    对于开发人员来说,构建一个消费应用程序时去了解各种各样的 API 是一个巨大的挑战.在你的 Web API 项目中使用 Swagger 的 .NET Core 封装 Swashbuckle 可以帮助你 ...

  4. ASP.NET Core 中文文档 第二章 指南 (09) 使用 Swagger 生成 ASP.NET Web API 在线帮助测试文档

    原文:ASP.NET Web API Help Pages using Swagger 作者:Shayne Boyer 翻译:谢炀(kiler) 翻译:许登洋(Seay) 对于开发人员来说,构建一个消 ...

  5. 在ASP.NET Core Web API上使用Swagger提供API文档

    我在开发自己的博客系统(http://daxnet.me)时,给自己的RESTful服务增加了基于Swagger的API文档功能.当设置IISExpress的默认启动路由到Swagger的API文档页 ...

  6. ASP.NET Core Web API中使用Swagger

    本节导航 Swagger介绍 在ASP.NET CORE 中的使用swagger   在软件开发中,管理和测试API是一件重要而富有挑战性的工作.在我之前的文章<研发团队,请管好你的API文档& ...

  7. 如何在ASP.NET Core Web API测试中使用Postman

    使用Postman进行手动测试 如果您是开发人员,测试人员或管理人员,则在构建和使用应用程序时,有时了解各种API方法可能是一个挑战. 使用带有.NET Core的Postman为您的Web API生 ...

  8. List多个字段标识过滤 IIS发布.net core mvc web站点 ASP.NET Core 实战:构建带有版本控制的 API 接口 ASP.NET Core 实战:使用 ASP.NET Core Web API 和 Vue.js 搭建前后端分离项目 Using AutoFac

    List多个字段标识过滤 class Program{  public static void Main(string[] args) { List<T> list = new List& ...

  9. 或许是你应该了解的一些 ASP.NET Core Web API 使用小技巧

    一.前言 在目前的软件开发的潮流中,不管是前后端分离还是服务化改造,后端更多的是通过构建 API 接口服务从而为 web.app.desktop 等各种客户端提供业务支持,如何构建一个符合规范.容易理 ...

随机推荐

  1. git中报错---fatal: pathspec 'readme.txt' did not match any files

    1.git安装 git官网下载最新版本,一键安装或custom install. 2.会弹出一个类似的命令窗口的东西,就说明Git安装成功. 3.安装完成后,还需要最后一步设置,在命令行输入如下--- ...

  2. java对象引用测试

    代码 java中初始化一个实例,这个实例对应的只是对象的一个地址,并不是对象本身.将这个实例赋值给别的实例时,新实例也是指向对象的地址,两个实例实际指向的是同一个实例.对新实例赋值,老实例也会同时改变 ...

  3. PHP 微信公众号/小程序获取openid,用户信息

    1.获取code (获得openid的前置条件) 地址:https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redi ...

  4. go语言之map

    go语言的map就相当于python的dict 1.map的初始化 //创建map //k的类型是int,v的类型是string var test25_1 map[int]string fmt.Pri ...

  5. Java题库——Chapter13抽象类和接口

    )What is the output of running class Test? public class Test { public static void main(String[ ] arg ...

  6. 双系统卸载ubuntu

    转载自https://www.jianshu.com/p/30795695be95 如果开机是这样子的,就是ubuntu引导windows(专业名词gpt) ubuntu引导windows 那么先进w ...

  7. Asp .Net Core Excel导入和导出

    ASP .Net Core使用EPPlus实现Api导入导出,这里使用是EPPlus 4.5.2.1版本,.Net Core 2.2.在linux上运行的时候需要安装libgdiplus . 下面我们 ...

  8. 一起学Android之ContentProvider

    本文主要讲解在Android开发中ContentProvider的常规用法,仅供学习分享使用,如有不足之处,还请指正. 访问一个ContentProvider 在Android开发中,应用程序通过Co ...

  9. Django注意知识点(二)

    Tinymce富文本 前台和后台的使用 一,后台 Admin 1. 于 settings.py 文件中修改 INSTALLED_APPS 2. 于 settings.py 文件中增添如下配置 # 富文 ...

  10. Flutter学习笔记(6)--Dart流程控制语句

    如需转载,请注明出处:Flutter学习笔记(5)--Dart流程控制语句 条件语句:if.if...elseif.if...elseif...else ; ) { print('优秀'); } &g ...