最好的总会在不经意间出现。前端
做为后端程序员,免不了与前端同事对接API, 一个书写良好的API设计文档可有效提升与前端对接的效率。程序员
为避免联调时来回撕逼,今天咱们聊一聊正确使用Swaager的姿式。json
在ConfigureServices
配置Swagger文档,在Configure
启用中间件后端
// Install-Package Swashbuckle.AspNetCore 略 services.AddSwaggerGen( options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "EAP API", Version = "v1" }); } ); --- app.UseSwagger(); app.UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/v1/swagger.json", "EAP API"); });
应用会在/Swagger
页面加载最基础的API文档。服务器
以一个最简单的Post请求为例,细数这最基础SwaggerUI的弊病app
[HttpPost] public async Task<bool> AddHotmapAsync([FromBody] CreateHotmapInput createHotmapInput) { var model = ObjectMapper.Map<CreateHotmapInput, Hotmap>(createHotmapInput); model.ProfileId = CurrentUser.TenantId; return await _hotmaps.InsertAsync(model)!= null; }
产生如图示SwaggerUI:
async
下文就来根治这些顽疾, 书写一个自述性、优雅的API文档。this
三下五除二,给出示例:设计
/// <summary> /// 添加热力图 /// </summary> /// <remarks> /// Sample request: /// ``` /// POST /hotmap /// { /// "displayName": "演示名称1", /// "matchRule": 0, /// "matchCondition": "https://www.cnblogs.com/JulianHuang/", /// "targetUrl": "https://www.cnblogs.com/JulianHuang/", /// "versions": [ /// { /// "versionName": "ver2020", /// "startDate": "2020-12-13T10:03:09", /// "endDate": "2020-12-13T10:03:09", /// "offlinePageUrl": "3fa85f64-5717-4562-b3fc-2c963f66afa6", // 没有绑定图片和离线网页的对应属性传 null /// "pictureUrl": "3fa85f64-5717-4562-b3fc-2c963f66afa6", /// "createDate": "2020-12-13T10:03:09" /// } /// ] /// } ///``` /// </remarks> /// <param name="createHotmapInput"></param> /// <returns></returns> [Consumes("application/json")] [Produces("text/plan")] [ProducesResponseType(typeof(Boolean), 200)] [HttpPost] public async Task<bool> AddHotmapAsync([FromBody] CreateHotmapInput createHotmapInput) { var model = ObjectMapper.Map<CreateHotmapInput, Hotmap>(createHotmapInput); model.ProfileId = CurrentUser.TenantId; return await _hotmaps.InsertAsync(model)!=null; }
注意若是注释内容包含代码,能够使用Markdown的代码语法```,在注释里面优雅显示代码.code
Consumes
,Produces
特性指示action接收和返回的数据类型,也就是媒体类型。Consumes、Produces是指示请求/响应支持的content types的过滤器,位于Microsoft.AspNetCore.Mvc命名空间下。
ProducesResponseType
特性指示服务器响应的预期内容和状态码API文档结果:
这样的SwaggerUI才正确表达了后端程序员的心里输出。
<GenerateDocumentationFile>true</GenerateDocumentationFile>
AddSwaggerGen
方法添加下行,启用注释文件// Set the comments path for the Swagger JSON and UI. var xmlFile = $"{this.GetType().Assembly.GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); opt.IncludeXmlComments(xmlPath);
这里啰嗦一下,若是是Abp Vnext解决方案(API是定义在HttpApi项目/Application项目),故咱们要为Abp Vnext解决方案加载带xml注释的Swagger Json,须要指示xmlFile为HttpApi.xml或者applicaiton.xml
以上就是小码甲总结的书写Swagger文档的优雅姿式:
API自述,约束输入输出,前端同事不再会追着你撕逼了!