標籤:程式 前後端分離 play ase pipeline xxxx head private 拷貝
關於為什麼用Swagger
目前稍微有點規模的公司,已經從原先的瀑布流開發到了敏捷開發,實現前後端分離,為此後端工程師只關注寫好Api即可,那程式員最討厭的就是寫Api文檔了,故而產生了Swagger。
Swagger原理
Swagger就是利用反射技術遍曆所有Api介面,並且從xml檔案中讀取注釋,在利用Swagger內建的模板組合html顯示至用戶端實現介面可視化,並且可調用。
Asp.net WebApi Swagger整合
1:vs2017,建立web項目,選擇WebApi
2:刪除Views、Scripts、Models、fonts、Content、Areas目錄
3:刪除RouteConfig.cs、FilterConfig.cs、BundleConfig.cs
4:刪除HomeController.cs
5:Global.asax中刪除異常代碼
6:nuget搜尋Swagger,安裝 Swashbuckle,Swagger.Net.UI
7:右鍵項目——》屬性——》產生——》輸出——》勾選XML文檔檔案——》儲存
8:修改SwaggerConfig.cs
新增方法,釋放c.IncludeXmlComments(GetXmlCommentsPath());的注釋(注意:例如傳回值為對象,然後又不在同一個項目,則需要多次調用)
private static string GetXmlCommentsPath(){ eturn System.String.Format(@"{0}\bin\{項目名稱}.XML", System.AppDomain.CurrentDomain.BaseDirectory);}
9:右鍵項目NuGet——》已安裝——》搜尋Swagger,卸載Swagger.Net.UI——》選項勾選強制卸載,點擊卸載。卸載Swagger.Net
10:然後在url地址中:例如:http://localhost:port/swagger即可
Swagger進階
1:當有dto項目時,此時dto也需要把注釋打到用戶端,注意dto項目也參考上面第7點產生xml檔案,複製第8點的方法
2:Swagger新增Header資訊,在上方注釋的地方加入:c.OperationFilter<HttpHeaderFilter>(); 拷貝下方代碼
public class HttpHeaderFilter : IOperationFilter { public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) { if (operation.parameters == null) operation.parameters = new List<Parameter>(); var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline(); //判斷是否添加許可權過濾器 var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Instance) .Any(filter => filter is ErpFilterAttribute); //判斷是否允許匿名方法 //var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any(); if (isAuthorized) { operation.parameters.Add(new Parameter { name = "AppId", @in = "header", description = "應用ID(機構編號)", required = false, type = "string" }); operation.parameters.Add(new Parameter { name = "Version", @in = "header", description = "版本號碼", required = false, type = "string" }); operation.parameters.Add(new Parameter { name = "Ts", @in = "header", description = "時間戳記", required = false, type = "string" }); operation.parameters.Add(new Parameter { name = "Lang", @in = "header", description = "語言套件", required = false, type = "string" }); operation.parameters.Add(new Parameter { name = "Sign", @in = "header", description = "簽名", required = false, type = "string" }); return; } } }
View Code
3:注釋的用法
注釋的用法,在API介面中"///"三斜杠注釋的summary為介面名注釋,summary下斷行符號<remarks>為備忘,注意每個欄位的注釋必須要全面,否則無法顯示完全
參考代碼如下
/// <summary> /// 角色 分頁列表 /// </summary> /// <remarks> /// Code傳回值說明: /// /// 錯誤碼地址:http://xxxx.com/ /// /// </remarks> /// <param name="conditionModel">分頁查詢條件</param> /// <returns></returns> [HttpGet, Route("api/ClientRoles")] public OutputModel<PagingOutputModel<List<BaseRoleDto>>> GetRoleList([FromUri]PagingInputModel conditionModel){ return null;}
View Code
圖片展示
Asp.Net WebApi Swagger終極搭建