Asp.Net Core Easy Series -5 interface documentation automatically generated using the Swagger

 

Foreword

    Currently on the market mainstream development model, almost all the way around the end of the separation, as a server developer, we have an obligation to provide each client to develop a good document to facilitate docking, reducing communication time and improve development efficiency; for developers speaking, writing interface documentation need to consume a lot of time, and write a manual-document interface due to frequent changes in demand become difficult to maintain, requiring a can automatically monitor interface input parameter in interface development stage, the automatic generation of documents ; due to the emergence Swagger plug-in, the work is almost fully automated.

1. What is the Swagger

    Swagger is SmartBear developed an API documentation automation tool, which uses Apache 2.0 free and open source license, allowing anyone free access to the tool, using the characteristics Swagger, you can easily generate visualization without any realization of the logic of the situation and resources and API interface, Swagger Category navigation API support, to provide API test suite, fully customizable for developers and API consumers are very friendly.

2. Start using Swagger
  • 2.1 First create a Asp.Net Core API project, and cited Swagger package from the NuGet

  • 2.2 Right-click on the item "dependency", select "Manage NuGet package (N)", this browser tab enter the name of the installation package, you can select the stable version, here I chose the version 4.0.1

Swashbuckle.AspNetCore
Swashbuckle.AspNetCore.Annotations

  • 2.3 First, we want to set up the project, ensure that the XML document generation projects, as shown below
    , right-click on the project - Properties - generation, check the "XML document file"

  • 2.4 Next in the pipeline need to add Startup.cs Swagger
        static string[] docs = new[] { "未分类" };

        public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); if (Env.IsDevelopment()) { services.AddSwaggerGen(options => { foreach (var doc in docs) options.SwaggerDoc(doc, new Info { Version = doc }); options.DocInclusionPredicate((docName, description) => { description.TryGetMethodInfo(out MethodInfo mi); var attr = mi.DeclaringType.GetCustomAttribute<ApiExplorerSettingsAttribute>(); if (attr != null) { return attr.GroupName == docName; } else { return docName == "未分类"; } }); options.CustomSchemaIds(d => d.FullName); options.IncludeXmlComments("Ron.SwaggerTest.xml", true); }); } } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger() .UseSwaggerUI(options => { options.DocumentTitle = "Ron.liang Swagger 测试文档"; foreach (var item in docs) options.SwaggerEndpoint($"/swagger/{item}/swagger.json", item); }); } app.UseMvc(); } }
  • 2.5 以上代码首先定义了一个常量,表示文档分类列表,默认值给了一个 “未分类”,然后在 ConfigureServices 和 Configure 方法中判断是开发环境才会引用 Swagger 进行 API 文档的生成,之所以要增加一个 “未分类”,是因为在我们没有对 API 进行分组的时候,默认把未分组的 API 归并到此分类下,好了,现在运行项目

  • 2.6 这浏览器中输入地址
http://localhost:5000/swagger/index.html
  • 看到 API 文档已经成功生成

  • 可以看到,各种不同的 HttpMethod 都有不同的颜色进行区分显示,点击该 API ,可以看到详细的输入参数,点击 API 接口右边的 Try it out ,还可以对接口进行实时测试,是不是觉得有一中连单元测试都免了的感觉。

  • 在上图中,红圈部分是我们编写的 xml 注释,可以看到,都被完整的抓取并显示出来了
3. 定义 API 分组
  • 上面是默认的 API 文档,在实际开发中,肯定需要对 API 进行分组和完善输出参数给消费者,现在就来对 Controller 进行改进,首先是设置分组名称

  • 3.1 定义分组
    [Route("api/[controller]"), ApiExplorerSettings(GroupName = "演示分组")]
    [ApiController]
    public class ValuesController : ControllerBase
  • 上面的代码在 ValuesController 上增加了一个特性 ApiExplorerSettings(GroupName = "演示分组"),这样就完成了一个分组设置;不过,如果希望该分组能在浏览器中显示,我们还需要在 Startup.cs 中定义的 docs 数组中增加 "演示分组" 名称
 static string[] docs = new[] { "未分类", "演示分组" };
4. 定义 API 接口友好名称
  • 4.1 下面对每个接口进行友好名称显示的定义,通过编写 xml 注释,并在 summary 节点书写接口名称,即可自动显示到 API 文档上面
        /// <summary>
        /// 获取数组 /// </summary> /// <remarks> /// <code> /// 输出参数:["value1", "value2"] /// </code> /// </remarks> /// <returns></returns> [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; }
  • 4.2 刷新网页,可以看到,接口友好名称已经显示出了了

结语

  • Swagger 基础应用可以帮助我们做到以下内容,现在就开始应用到程序中吧
  • 自动生成 API 文档
  • 对每个控制器进行分组
  • 自动抓取开发人员编写的 XML 注释
  • 在 API 文档界面进行即时测试
  • 还有很多过滤等功能,下次有机会再试试

源码下载

https://github.com/lianggx/EasyAspNetCoreDemo/tree/master/Ron.SwaggerTest

微信公众号:DotNet程序园
欢迎关注收取阅读最新文章
  • 您随手点赞是我不断书写的动力,如有错误,欢迎指正
  • 出处:http://www.cnblogs.com/viter/
  • 推荐一个快速开发脚手架,基于 .netcore+pgsql,GitHub地址: https://github.com/lianggx/mystaging
  • 本文版权归作者和博客园共有,欢迎个人转载,必须保留此段声明;商业转载请联系授权,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 欢迎大家关注我的微信公众号,一起学习一起进步
 
标签:  swagger

 

前言

    目前市场上主流的开发模式,几乎清一色的前后端分离方式,作为服务端开发人员,我们有义务提供给各个客户端良好的开发文档,以方便对接,减少沟通时间,提高开发效率;对于开发人员来说,编写接口文档需要消耗大量的时间,并且,手动编写的文档接口会由于需求的频繁变动变得难以维护,这就需要一个在接口开发阶段可以自动监测接口输入参数,自动生成文档的功能;由于 Swagger 插件的出现,这项工作几乎可以实现完全的自动化。

1. 什么是 Swagger

    Swagger 是由 SmartBear 公司开发的一款 API 文档自动化工具,其采用 Apache 2.0 免费开源授权协议,允许任何人免费使用该工具,利用 Swagger 的特性,可以很方便在没有任何实现逻辑的情况下生成可视化和与API资源交互界面,Swagger 支持 API 分类导航,提供 API 测试套件,完全的可定制化,对开发人员和 API 消费者都非常友好。

2. 开始使用 Swagger
  • 2.1 首先建立一个 Asp.Net Core API 项目,并从 NuGet 上引用 Swagger 包

  • 2.2 右键点击项目“依赖项”,选择 “管理 NuGet 程序包(N)”,这浏览标签页输入包名进行安装,选择稳定版即可,此处我选择的版本是 4.0.1

Swashbuckle.AspNetCore
Swashbuckle.AspNetCore.Annotations

  • 2.3 首先我们要对项目进行设置,确保生成项目的 XML 文档,如下图
    右键点击项目-属性-生成,勾选 "XML 文档文件"

  • 2.4 接下来需要在 Startup.cs 中将 Swagger 加入管道中
        static string[] docs = new[] { "未分类" };

        public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); if (Env.IsDevelopment()) { services.AddSwaggerGen(options => { foreach (var doc in docs) options.SwaggerDoc(doc, new Info { Version = doc }); options.DocInclusionPredicate((docName, description) => { description.TryGetMethodInfo(out MethodInfo mi); var attr = mi.DeclaringType.GetCustomAttribute<ApiExplorerSettingsAttribute>(); if (attr != null) { return attr.GroupName == docName; } else { return docName == "未分类"; } }); options.CustomSchemaIds(d => d.FullName); options.IncludeXmlComments("Ron.SwaggerTest.xml", true); }); } } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger() .UseSwaggerUI(options => { options.DocumentTitle = "Ron.liang Swagger 测试文档"; foreach (var item in docs) options.SwaggerEndpoint($"/swagger/{item}/swagger.json", item); }); } app.UseMvc(); } }
  • 2.5 以上代码首先定义了一个常量,表示文档分类列表,默认值给了一个 “未分类”,然后在 ConfigureServices 和 Configure 方法中判断是开发环境才会引用 Swagger 进行 API 文档的生成,之所以要增加一个 “未分类”,是因为在我们没有对 API 进行分组的时候,默认把未分组的 API 归并到此分类下,好了,现在运行项目

  • 2.6 这浏览器中输入地址
http://localhost:5000/swagger/index.html
  • 看到 API 文档已经成功生成

  • 可以看到,各种不同的 HttpMethod 都有不同的颜色进行区分显示,点击该 API ,可以看到详细的输入参数,点击 API 接口右边的 Try it out ,还可以对接口进行实时测试,是不是觉得有一中连单元测试都免了的感觉。

  • 在上图中,红圈部分是我们编写的 xml 注释,可以看到,都被完整的抓取并显示出来了
3. 定义 API 分组
  • 上面是默认的 API 文档,在实际开发中,肯定需要对 API 进行分组和完善输出参数给消费者,现在就来对 Controller 进行改进,首先是设置分组名称

  • 3.1 定义分组
    [Route("api/[controller]"), ApiExplorerSettings(GroupName = "演示分组")]
    [ApiController]
    public class ValuesController : ControllerBase
  • 上面的代码在 ValuesController 上增加了一个特性 ApiExplorerSettings(GroupName = "演示分组"),这样就完成了一个分组设置;不过,如果希望该分组能在浏览器中显示,我们还需要在 Startup.cs 中定义的 docs 数组中增加 "演示分组" 名称
 static string[] docs = new[] { "未分类", "演示分组" };
4. 定义 API 接口友好名称
  • 4.1 下面对每个接口进行友好名称显示的定义,通过编写 xml 注释,并在 summary 节点书写接口名称,即可自动显示到 API 文档上面
        /// <summary>
        /// 获取数组 /// </summary> /// <remarks> /// <code> /// 输出参数:["value1", "value2"] /// </code> /// </remarks> /// <returns></returns> [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; }
  • 4.2 刷新网页,可以看到,接口友好名称已经显示出了了

结语

  • Swagger 基础应用可以帮助我们做到以下内容,现在就开始应用到程序中吧
  • 自动生成 API 文档
  • 对每个控制器进行分组
  • 自动抓取开发人员编写的 XML 注释
  • 在 API 文档界面进行即时测试
  • 还有很多过滤等功能,下次有机会再试试

源码下载

https://github.com/lianggx/EasyAspNetCoreDemo/tree/master/Ron.SwaggerTest

Guess you like

Origin www.cnblogs.com/hmit/p/11363412.html