本文共 4357 字,大约阅读时间需要 14 分钟。
Swagger也算是行之有年的API文件生成器,只要在API上使用C#的<summary />
文件注解标签,就可以产生精美的线上文件,并且对RESTful API有良好的支持。不仅支持生成文件,还支持模拟调用的交互功能,连Postman都不用打开就能测API。
要在ASP.NET Core使用Swagger需要安装Swashbuckle.AspNetCore
套件。
dotnet add package Swashbuckle.AspNetCore
在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(); }}
SwaggerDocument
物件。 SwaggerDocument
物件。可以从URL查看Swagger产生器产生的SwaggerDocument
物件。http://localhost:5000/swagger/v1/swagger.json
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) { // ... }}
老司机发车啦: