目前市場上主流的開發模式,幾乎清一色的先後端分離方式,做爲服務端開發人員,咱們有義務提供給各個客戶端良好的開發文檔,以方便對接,減小溝通時間,提升開發效率;對於開發人員來講,編寫接口文檔須要消耗大量的時間,而且,手動編寫的文檔接口會因爲需求的頻繁變更變得難以維護,這就須要一個在接口開發階段能夠自動監測接口輸入參數,自動生成文檔的功能;因爲 Swagger 插件的出現,這項工做幾乎能夠實現徹底的自動化。html
Swagger 是由 SmartBear 公司開發的一款 API 文檔自動化工具,其採用 Apache 2.0 免費開源受權協議,容許任何人無償使用該工具,利用 Swagger 的特性,能夠很方便在沒有任何實現邏輯的狀況下生成可視化和與API資源交互界面,Swagger 支持 API 分類導航,提供 API 測試套件,徹底的可定製化,對開發人員和 API 消費者都很是友好。git
Swashbuckle.AspNetCore Swashbuckle.AspNetCore.Annotations
static string[] docs = new[] { "未分類" }; public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); if (Env.IsDevelopment()) { services.AddSwaggerGen(options => { foreach (var doc in docs) options.SwaggerDoc(doc, new Info { Version = doc }); options.DocInclusionPredicate((docName, description) => { description.TryGetMethodInfo(out MethodInfo mi); var attr = mi.DeclaringType.GetCustomAttribute<ApiExplorerSettingsAttribute>(); if (attr != null) { return attr.GroupName == docName; } else { return docName == "未分類"; } }); options.CustomSchemaIds(d => d.FullName); options.IncludeXmlComments("Ron.SwaggerTest.xml", true); }); } } // 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.UseSwagger() .UseSwaggerUI(options => { options.DocumentTitle = "Ron.liang Swagger 測試文檔"; foreach (var item in docs) options.SwaggerEndpoint($"/swagger/{item}/swagger.json", item); }); } app.UseMvc(); } }
http://localhost:5000/swagger/index.html
上面是默認的 API 文檔,在實際開發中,確定須要對 API 進行分組和完善輸出參數給消費者,如今就來對 Controller 進行改進,首先是設置分組名稱github
[Route("api/[controller]"), ApiExplorerSettings(GroupName = "演示分組")] [ApiController] public class ValuesController : ControllerBase
static string[] docs = new[] { "未分類", "演示分組" };
/// <summary> /// 獲取數組 /// </summary> /// <remarks> /// <code> /// 輸出參數:["value1", "value2"] /// </code> /// </remarks> /// <returns></returns> [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; }
https://github.com/lianggx/EasyAspNetCoreDemo/tree/master/Ron.SwaggerTestjson