最近我們團隊一直進行.net core的轉型,web開發向着前后端分離的技術架構演進,我們后台主要是采用了asp.net core webapi來進行開發,開始每次調試以及與前端人員的溝通上都存在這效率低下的問題,一次在看微軟asp.net core官方文檔的時候,發現了swagger這個好東西。然后在實際的項目中引入了該技術。我們開發人員測試自己寫的api的過程大大得到了簡化,前端人員也可以根據我們提供的swagger help pages 自己進行一些前端代碼的測試,大大提高了前后端的開發效率。下面我就拿我自己的真實上線項目來一步一步的講解如何在asp.net core webapi中引入swagger。(也可以參照微軟官方文檔:https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/web-api-help-pages-using-swagger)
一、引入swagger Nuget包
右鍵點擊wepapi項目的依賴項,點擊管理Nuget程序包,如下圖:
在打開的NuGet包程序管理界面,輸入:Swashbuckle.AspNetCore 目前該程序包的版本為1.0.0,點擊安裝。
安裝完后,需要在項目中的Startup.cs文件中進行配置。
二、配置Swagger
打開Startup.cs 文件,在ConfigureServices 方法中,添加如下代碼:
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "TwBusManagement接口文檔", Description = "RESTful API for TwBusManagement", TermsOfService = "None", Contact = new Contact { Name = "Alvin_Su", Email = "asdasdasd@outlook.com", Url = "" } }); //Set the comments path for the swagger json and ui. var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "twbusapi.xml"); c.IncludeXmlComments(xmlPath); // c.OperationFilter<HttpHeaderOperation>(); // 添加httpHeader參數 });
注意上段代碼的最后三行,是我們api描述文檔xml的生成地址和文件名,需要在項目的屬性中進行配置。如下圖:
另外上圖中,禁止顯示警告中,添加1591 代碼,可以過濾掉一些類名沒有寫注釋的報警信息。
最后需要在Configure方法中,添加如下代碼,注意下面的代碼必須添加在 app.UseMvc() 前面:
// Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "TwBusManagement API V1"); c.ShowRequestHeaders(); });
以上配置完后,就可以使用Swagger生成的幫助頁面了,運行項目后,在瀏覽器地址 加上后綴 /swagger就可以跳轉到幫助頁面:
當然我們開發人員在開發項目的過程中並不想每次都要手動輸入地址才能跳轉到幫助頁面,這樣太麻煩。我們可借助visual studio 進行跳轉,如下圖:
打開 launchSettings.json 文件,把webapi項目的啟動路徑設置成 swagger。這樣每次調試運行項目都會自動跳轉到swagger幫助頁面
三、Swagger的一些高級用法
Swagger非常強大,不僅僅是一些幫助頁面信息,還可以進行api的調試。這樣就可以不用借助第三方工具 如:postman,進行webapi的調試。swagger經過配置,還可以輸入一些http頭部信息,如權限認證信息等。下面就來講解以下具體的配置。
首先我們需要新建一個類 HttpHeaderOperation,讓該類繼承IOperationFilter 接口,該接口需引入命名空間:Swashbuckle.AspNetCore.SwaggerGen,實現接口方法Apply 代碼如下:
public class HttpHeaderOperation : IOperationFilter { public void Apply(Operation operation, OperationFilterContext context) { if (operation.Parameters == null) { operation.Parameters = new List<IParameter>(); } var actionAttrs = context.ApiDescription.ActionAttributes(); var isAuthorized= actionAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute)); if (isAuthorized == false) //提供action都沒有權限特性標記,檢查控制器有沒有 { var controllerAttrs= context.ApiDescription.ControllerAttributes(); isAuthorized= controllerAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute)); } var isAllowAnonymous = actionAttrs.Any(a => a.GetType() == typeof(AllowAnonymousAttribute)); if (isAuthorized && isAllowAnonymous == false) { operation.Parameters.Add(new NonBodyParameter() { Name = "Authorization", //添加Authorization頭部參數 In = "header", Type = "string", Required = false }); } } }
然后在 Startup.cs 中的 ConfigureServices 方法,找到之前的AddSwaggerGen 代碼段,在最后添加如下代碼:
c.OperationFilter<HttpHeaderOperation>()
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "TwBusManagement接口文檔", Description = "RESTful API for TwBusManagement", TermsOfService = "None", Contact = new Contact { Name = "Alvin_Su", Email = "alvin_su@outlook.com", Url = "" } }); //Set the comments path for the swagger json and ui. var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "twbusapi.xml"); c.IncludeXmlComments(xmlPath); c.OperationFilter<HttpHeaderOperation>(); // 添加httpHeader參數 });
這樣,我們允許webapi項目后,就可以輸入 Authorization 頭部參數了。如下圖:
更多關於Swagger的用法可以參考https://github.com/domaindrivendev/Swashbuckle.AspNetCore 以及微軟文檔:https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/web-api-help-pages-using-swagger