Swagger 是一个规范且完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。
Swagger 的目标是对 REST API 定义一个标准且和语言无关的接口,可以让人和计算机拥有无需访问源码、文档或网络流量监测就可以发现和理解服务的能力。当通过 Swagger 进行正确定义,用户可以理解远程服务并使用最少实现逻辑与远程服务进行交互。与为底层编程所实现的接口类似,Swagger 消除了调用服务时可能会有的猜测。
Swagger 的优势
- 支持 API 自动生成同步的在线文档:使用 Swagger 后者可以直接通过代码生成文档,不再需要自己手动编写接口文档了,对程序员来说非常方便,可以节约写文档的时间去学习新技术。
- 提供 Web 页面在线测试 API:光有文档还不够,Swagger 生成的文档还支持在线测试。参数和格式都定好了,直接在界面上输入参数对应的值即可在线测试接口。
实战演示
1、新建一个asp.net core web api项目
2、Nuget安装Swagger
3、为接口及接口中用到的类添加注释
4、右键项目属性(如果项目中有其他库的,都需要参照配置下)生成XML文档,如下图打勾保存
5、Startup配置Swagger,这里用到了一个自定义的扩展类:SwaggerHttpHeaderOperation,这个类里面增加了调试的Http请求header参数,比如Token就可以扩展下,这样在调试时就可以填写该参数,方便调试需要鉴权的接口。
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Text;
namespace ZQSwaggerDemo
{
public class Startup
{
const string PROJECTNAME = "知擎物联API";
const string VERSION = "v1.0.0";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
//配置swagger
StringBuilder fDescription = new StringBuilder();
fDescription.Append("<a target='_blank' href='https://www.yyzq.net' class='link'>常州知擎物联科技有限公司 版权所有</a>");
fDescription.Append(#34;<br>API适用标注说明:");
fDescription.Append(#34;<br><span style='color:blue'>【NOTOKEN】</span>:无需登录可访问");
services.AddSwaggerGen(c =>
{
c.OperationFilter<SwaggerHttpHeaderOperation>();
c.SwaggerDoc(VERSION, new Microsoft.OpenApi.Models.OpenApiInfo()
{
Title = PROJECTNAME,
Version = VERSION,
Description = ""
}); ;
//加载注释xml文件(这里演示的代码是为了方便一次性加载多个XML文档,省去了一个个XML文件添加的繁琐)
string[] files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "ZQ*.xml");
foreach (string item in files)
{
c.IncludeXmlComments(item);
}
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();//启用中间件服务生成Swagger作为JSON终结点
app.UseSwaggerUI(c =>
{
//启用中间件服务对swagger-ui,指定Swagger JSON终结点
c.SwaggerEndpoint(#34;/swagger/{VERSION}/swagger.json", PROJECTNAME);
});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace ZQSwaggerDemo
{
/// <summary>
/// Swagger调试header
/// </summary>
public class SwaggerHttpHeaderOperation : IOperationFilter
{
/// <summary>
///
/// </summary>
/// <param name="operation"></param>
/// <param name="context"></param>
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
operation.Parameters.Add(new OpenApiParameter()
{
Name = "Token",
In = ParameterLocation.Header,
Required = false,
Schema = new OpenApiSchema { Type = "string" }
});
}
}
}
6、启动项目,访问:http://localhost:45039/swagger/index.html 可以看到之前写的注释都在文档中体现了出来
7、调试接口,对想要调试的接口,展开接口后,点击Try it out按钮,这里我们可以看到之前扩展的Header部分参数(本DEMO仅示范,并未使用,实际项目中还是经常需要自定义一些header参数),填写好参数后,点击Execute调用接口,可以看到成功返回了数据。
欢迎大家交流评论,共同进步,有任何建议或问题随时私聊我
如果本文对您有帮助,请关注,点赞,这是对我继续分享技术最好的鼓励。
有需要本文DEMO的,私聊关键字:SwaggerDEMO