.NET Core使用swagger進行API介面文件管理
一、問題背景
隨著技術的發展,現在的開發模式已經更多的轉向了前後端分離的模式,在前後端開發的過程中,聯絡的方式也變成了API介面,但是目前專案中對於API的管理很多時候還是通過手工編寫文件,每次的需求變更只要涉及到介面的變更,文件都需要進行額外的維護,如果有哪個小夥伴忘記維護,很多時候就會造成一連續的問題,那如何可以更方便的解決API的溝通問題?Swagger給我們提供了一個方式,由於目前主要我是投入在.NET Core專案的開發中,所以以.NET Core作為示例
二、什麼是Swagger
Swagger可以從不同的程式碼中,根據註釋生成API資訊,swagger擁有強大的社群,並且對於各種語言都支援良好,有很多的工具可以通過swagger生成的檔案生成API文件
三、.NET Core中使用
.NET Core中使用首先要用nuget引用Swashbuckle.AspNetCore,在startup.cs中加入如下程式碼
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Hello", Version = "v1" }); var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "WebApplication2.xml"); c.IncludeXmlComments(xmlPath); }); services.AddMvcCore().AddApiExplorer(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvcWithDefaultRoute(); app.UseSwagger(c => { }); app.UseSwaggerUI(c => { c.ShowExtensions(); c.ValidatorUrl(null); c.SwaggerEndpoint("/swagger/v1/swagger.json", "test V1"); }); }
以上部分為載入swagger的程式碼,位於startup.cs中,下面是controller程式碼:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace WebApplication2.Controllers { /// <summary> /// 測試資訊 /// </summary> [Route("api/[controller]/[action]")] public class ValuesController : Controller { /// <summary> /// 獲取所有資訊 /// </summary> /// <returns></returns> [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } /// <summary> /// 根據ID獲取資訊 /// </summary> /// <param name="id"></param> /// <returns></returns> // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } /// <summary> /// POST了一個數據信息 /// </summary> /// <param name="value"></param> // POST api/values [HttpPost] public void Post([FromBody]string value) { } /// <summary> /// 根據ID put 資料 /// </summary> /// <param name="id"></param> /// <param name="value"></param> // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } /// <summary> /// 根據ID刪除資料 /// </summary> /// <param name="id"></param> // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } /// <summary> /// 複雜資料操作 /// </summary> /// <param name="id"></param> // DELETE api/values/5 [HttpPost] public namevalue test(namevalue _info) { return _info; } } public class namevalue { /// <summary> /// name的資訊 /// </summary> public String name { get; set; } /// <summary> /// value的資訊 /// </summary> public String value { get; set; } } }
接下來我們還需要在生成中勾上XML生成文件,如圖所示
接下去我們可以執行起來了,除錯,瀏覽器中輸入http://localhost:50510/swagger/,這裡埠啥的根據實際情況來,執行效果如下圖所示:
可以看到swagger將方法上的註釋以及實體的註釋都抓出來了,並且顯示在swaggerui,整體一目瞭然,並且可以通過try it按鈕進行簡單的除錯,但是在具體專案中,可能存在需要將某些客戶端資訊通過header帶到服務中,例如token資訊,使用者資訊等(我們專案中就需要header中帶上token傳遞到後端),那針對於這種情況要如何實現呢?可以看下面的做法
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Hello", Version = "v1" }); var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "WebApplication2.xml"); c.IncludeXmlComments(xmlPath); c.OperationFilter<AddAuthTokenHeaderParameter>(); }); services.AddMvcCore().AddApiExplorer(); }
public class AddAuthTokenHeaderParameter : IOperationFilter { public void Apply(Operation operation, OperationFilterContext context) { if (operation.Parameters == null) { operation.Parameters = new List<IParameter>(); } operation.Parameters.Add(new NonBodyParameter() { Name = "token", In = "header", Type = "string", Description = "token認證資訊", Required = true }); } }
我們在ConfigureServices添加了OperationFilter<AddAuthTokenHeaderParameter>(),通過這種方式我們可以在swagger中顯示token的header,並且進行除錯(如圖所示),AddAuthTokenHeaderParameter 的apply的屬性context中帶了controller以及action的各種資訊,可以配合實際情況使用
四、與其他API管理工具結合
swagger強大的功能以及社群的力量,目前很多的API管理工具都支援YApi,目前我們使用的是由去哪兒開源的YApi,從圖中可以看到YApi支援匯入swagger生成的JSON檔案,除該工具 之外DOClever(開源)也是一個不錯的API管理工具,也支援Swagger檔案匯入(具體工具用法,大家可以去看他們的官網)
五、總結
Swagger是一個很好的工具,並且在前後端分離開發越來越流行的情況下,在後續的開發過程中,我覺得會扮演著越來越重要的作用,目前我們公司小的專案已經準備開始使用swagger+yapi進行API的管理方式,而這篇文章也是這段時間抽空整理API管理的結果,希望可以幫助到大家,這裡可能有很多不足的地方,歡迎大家拍磚,也希望可以跟大家一起進步,非常感謝博主!!!