一问题背景
随着技术的发展, 现在的开发模式已经更多的转向了前后端分离的模式, 在前后端开发的过程中, 联系的方式也变成了 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 管理的结果, 希望可以帮助到大家, 这里可能有很多不足的地方, 欢迎大家拍砖, 也希望可以跟大家一起进步
来源: https://www.cnblogs.com/OMango/p/8460092.html