ASP.NET Core 2 学习笔记(十三)Swagger
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.cs
的ConfigureServices
加入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 { /// <summary> /// 查询使用者清单 /// </summary> /// <param name="q">查询使用者名称</param> /// <returns>使用者清单</returns> [HttpGet] public ResultModel Get(string q) { // ... } }
再次打开Swagger,会发现没有显示说明,因为没有设定.NET 的XML 文件目录,所以Swagger 抓不到说明是正常的。
打开*.csproj
,在<Project />
区块中插入以下代码:
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DocumentationFile>bin\Debug\netcoreapp2.0\Api.xml</DocumentationFile> <NoWarn>1591</NoWarn> </PropertyGroup>
以我示例的*.csproj
内容如下:
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp2.0</TargetFramework> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DocumentationFile>bin\Debug\netcoreapp2.0\Api.xml</DocumentationFile> <NoWarn>1591</NoWarn> </PropertyGroup> <ItemGroup> <Folder Include="wwwroot\" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.8" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="2.5.0" /> </ItemGroup> </Project>
然后在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 { /// <summary> /// 查询使用者清单 /// </summary> /// <param name="q">查询使用者名称</param> /// <returns>使用者清单</returns> [HttpGet] [ProducesResponseType(typeof(ResultModel<IEnumerable<UserModel>>), 200)] [ProducesResponseType(typeof(ResultModel<string>), 500)] public ResultModel<IEnumerable<UserModel>> Get(string q) { // ... } }
执行结果
参考
老司机发车啦:
下一篇: 让人哭笑不得的家长和宝宝
推荐阅读
-
Orleans[NET Core 3.1] 学习笔记(四)( 2 )获取Grain的方式
-
.NET Core 学习笔记2——管理nuget包
-
ASP.NET Core笔记(2) - 依赖注入
-
ASP.NET Core 2 学习笔记(十三)Swagger
-
ASP.NET Core 2 学习笔记(六)
-
ASP.NET Core 2 学习笔记(十二)REST-Like API
-
ASP.NET Core 2 学习笔记(十一)Cookies & Session
-
ABP框架(asp.net core 2.X+Vue)模板项目学习之路(一)
-
ASP.NET Core 2 学习笔记(九)模型绑定
-
张高兴的 Windows 10 IoT 开发笔记:部署 ASP.NET Core 2 应用