目前市场上主流的开发模式,几乎清一色的先后端分离方式,做为服务端开发人员,咱们有义务提供给各个客户端良好的开发文档,以方便对接,减小沟通时间,提升开发效率;对于开发人员来讲,编写接口文档须要消耗大量的时间,而且,手动编写的文档接口会因为需求的频繁变更变得难以维护,这就须要一个在接口开发阶段能够自动监测接口输入参数,自动生成文档的功能;因为 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