博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ASP.NET Core 2 学习笔记(十三)Swagger
阅读量:7262 次
发布时间:2019-06-29

本文共 4357 字,大约阅读时间需要 14 分钟。

原文:

Swagger也算是行之有年的API文件生成器,只要在API上使用C#的<summary />文件注解标签,就可以产生精美的线上文件,并且对RESTful API有良好的支持。不仅支持生成文件,还支持模拟调用的交互功能,连Postman都不用打开就能测API。

本篇将介绍如何通过Swagger产生ASP.NET Core的RESTful API文件。

安装套件

要在ASP.NET Core使用Swagger需要安装Swashbuckle.AspNetCore套件。

通过过.NET Core CLI在项目文件夹执行安装指令:

dotnet add package Swashbuckle.AspNetCore

注册Swagger

Startup.csConfigureServices加入Swagger的服务及Middleware。如下:

using Swashbuckle.AspNetCore.Swagger;// ...public class Startup{    public void ConfigureServices(IServiceCollection services)    {        services.AddMvc()                .AddJsonOptions(options => {                    options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;                });        services.AddSwaggerGen(c =>        {            c.SwaggerDoc(                // name: 关系到 SwaggerDocument 的 URL 位置。                name: "v1",                 // info: 是用于 SwaggerDocument 版本信息的提示(內容非必填)。                info: new Info                {                    Title = "RESTful API",                    Version = "1.0.0",                    Description = "This is ASP.NET Core RESTful API Sample.",                    TermsOfService = "None",                    Contact = new Contact {                         Name = "SnailDev",                         Url = "http://www.cnblogs.com/snaildev/"                     },                    License = new License {                         Name = "CC BY-NC-SA 4.0",                         Url = "https://creativecommons.org/licenses/by-nc-sa/4.0/"                     }                }            );        });    }        public void Configure(IApplicationBuilder app)    {        app.UseSwagger();        app.UseSwaggerUI(c =>        {            c.SwaggerEndpoint(                // url: 需配合 SwaggerDoc 的 name。 "/swagger/{SwaggerDoc name}/swagger.json"                url: "/swagger/v1/swagger.json",                 // name: 用于 Swagger UI 右上角选择不同版本的 SwaggerDocument 提示名称使用。                name: "RESTful API v1.0.0"            );        });        app.UseMvc();    }}
  • AddSwaggerGen
    Swagger生成器是负责取得API的规格并产生SwaggerDocument物件。
  • UseSwagger
    Swagger Middleware负责路由,提供SwaggerDocument物件。
    可以从URL查看Swagger产生器产生的SwaggerDocument物件。
    http://localhost:5000/swagger/v1/swagger.json
  • UseSwaggerUI
    SwaggerUI是负责将SwaggerDocument物件变成漂亮的界面。
    预设URL:http://localhost:5000/swagger

API沿用的示例程序。

设定完成后,启动网站就能开启Swagger UI 了。下面如下:

文件注解标签

在API加入<summary />文件注解标签。如下:

// ...[Route("api/[controller]s")]public class UserController : Controller{    ///     /// 查询使用者清单    ///     /// 查询使用者名称    /// 
使用者清单
[HttpGet] public ResultModel Get(string q) { // ... }} 

再次打开Swagger,会发现没有显示说明,因为没有设定.NET 的XML 文件目录,所以Swagger 抓不到说明是正常的。

打开*.csproj,在<Project />区块中插入以下代码:

bin\Debug\netcoreapp2.0\Api.xml
1591

以我示例的*.csproj内容如下:

netcoreapp2.0
bin\Debug\netcoreapp2.0\Api.xml
1591

然后在Swagger生成器设定读取<DocumentationFile>指定的XML文件目录位置:

// ...public class Startup{    public void ConfigureServices(IServiceCollection services)    {        // ...        services.AddSwaggerGen(c =>        {            // ...            var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "Api.xml");            c.IncludeXmlComments(filePath);        });    }}

返回格式

以RESTful API的例子来看,返回的格式都是JSON,所以可以直接在Controller加上[Produces("application/json")]表示返回的类型都是JSON,在Swagger的Response Content Type选项就会被锁定只有application/json可以使用。如下:

// ...[Route("api/[controller]s")][Produces("application/json")]public class UserController : Controller{    // ...}

返回类型

若有预期API在不同的HTTP Status Code时,会返回不同的对象,可以透过[ProducesResponseType(type)]定义返回的对象。在Swagger中就可以清楚看到该API可能会发生的HTTP Status Code及返回对象。例如:

// ...[Route("api/[controller]s")][Produces("application/json")]public class UserController : Controller{    ///     /// 查询使用者清单    ///     /// 查询使用者名称    /// 
使用者清单
[HttpGet] [ProducesResponseType(typeof(ResultModel
>), 200)] [ProducesResponseType(typeof(ResultModel
), 500)] public ResultModel
> Get(string q) { // ... }}

执行结果

参考

 

老司机发车啦: 

你可能感兴趣的文章
[LeetCode] Basic Calculator III 基本计算器之三
查看>>
python爬虫 赶集网
查看>>
Unix环境高级编程-阻塞访问原理——等待队列
查看>>
博客园页面源代码结构分析
查看>>
強化 Python 在 Vim 裡的顏色
查看>>
WPF实现物理效果 拉一个小球
查看>>
Win10 设置窗口背景色
查看>>
解决ionic 上拉加载组件 ion-infinite-scroll自动调用多次的问题或禁止第一次加载...
查看>>
函数柯里化 curry
查看>>
硬怼高晓松系列:大哥,你这么能吹,这次砸招牌了吧?
查看>>
Mysql 连接数,最大并发数设置
查看>>
Debug Hacks中文版——深入调试的技术和工具
查看>>
WPF触控程序开发(二)——整理的一些问题
查看>>
python selenium
查看>>
PHP超级全局变量、魔术变量和魔术函数的区别和联系
查看>>
洛谷P1730 最小密度路径(floyd)
查看>>
javascript和python取dict字典对象的不同
查看>>
Java 8 – Convert Instant to ZonedDateTime
查看>>
RabbitMQ 3.6.1 升级至 3.7.9 版本(Windows 升级至Centos)
查看>>
教务处管理系统(数据结构的简单应用)
查看>>