最好的總會在不經意間出現。前端
做爲後端程序員,免不了與前端同事對接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自述,約束輸入輸出,前端同事不再會追着你撕逼了!