随着技术的发展,现在的开发模式已经更多的转向了前后端分离的模式,在前后端开发的过程中,联系的方式也变成了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></param> /// <returns></returns> // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } /// <summary> /// POST了一个数据信息 /// </summary> /// <param></param> // POST api/values [HttpPost] public void Post([FromBody]string value) { } /// <summary> /// 根据ID put 数据 /// </summary> /// <param></param> /// <param></param> // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } /// <summary> /// 根据ID删除数据 /// </summary> /// <param></param> // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } /// <summary> /// 复杂数据操作 /// </summary> /// <param></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生成文档,如图所示
接下去我们可以运行起来了,调试,浏览器中输入: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(); }