ASP.NET Core 3.1 系列之 Web API 中间件篇 (四)
接口文档自动生成(Swagger) 使用教程
Swagger (OpenAPI) 是一个与语言无关的规范,用于描述 REST API。 它使计算机和用户无需直接访问源代码即可了解 REST API 的功能。
添加NuGet 包
包名称:Swashbuckle.AspNetCore
修改 Startup.cs 配置
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(); //添加Swagger
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger(); //启用Swagger
//访问地址 http://localhost:5000/swagger/index.html
app.UseSwaggerUI(); //启用Swagger UI页面
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
到此所有配置完成,启动应用程序,访问http://localhost:5000/swagger/index.html
高级使用
1.如何显示控制器注释
鼠标->项目右键->属性
修改 Startup.cs 类
services.AddSwaggerGen(c =>
{
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath, true); //true 显示控制器级别注释
});
2.如何显示更多接口描述信息
接口方法添加如下代码
/// <summary>
/// 测试方法
/// </summary>
/// <remarks>
/// 提交参数说明:
///
/// POST
/// {
/// "id": 主键ID,
/// "name": "用户姓名",
/// "pwd": "密码"
/// }
///
/// </remarks>
/// <returns></returns>
[HttpGet("GetHangfireTest")]
public IActionResult GetHangfireTest()
{
BackgroundJob.Enqueue(() => Console.WriteLine("队列任务"));
BackgroundJob.Schedule(() => Console.WriteLine("延后2分钟"), TimeSpan.FromMinutes(2));
RecurringJob.AddOrUpdate(() => Console.WriteLine("每分钟执行一下"), Cron.Minutely());
return Ok();
}
3.如何自定义Swagger访问地址
修改 Startup.cs 类
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "我的测试API");
c.RoutePrefix = "mytest/openapi"; //自定义访问路由
});
访问地址变更为:http://localhost:5000/mytest/openapi/index.html
4.如何自定义Swagger 文档标题等其他描述信息
修改 Startup.cs 类
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "测试API大标题",
Description = "测试API详细描述信息",
});
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath, true);
});
5.如何添加多个Swagger 文档
修改 Startup.cs 类
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "测试API大标题",
Description = "测试API详细描述信息",
});
c.SwaggerDoc("v2", new OpenApiInfo
{
Title = "测试API大标题2",
Description = "测试API详细描述信息2",
});
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath, true);
});
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "我的测试API");
c.SwaggerEndpoint("/swagger/v2/swagger.json", "我的测试API2");
c.RoutePrefix = "mytest/openapi";
});
效果如下
6.如何添加 Jwt 登陆认证
添加NuGet包:Swashbuckle.AspNetCore.Filters
修改 Startup.cs 类
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "测试API大标题",
Description = "测试API详细描述信息",
});
c.SwaggerDoc("v2", new OpenApiInfo
{
Title = "测试API大标题2",
Description = "测试API详细描述信息2",
});
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath, true);
//以下下是Jwt配置
c.OperationFilter<AddResponseHeadersFilter>();
c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
c.OperationFilter<SecurityRequirementsOperationFilter>();
c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Description = "Bearer {token}",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});
});
实现效果如下
更多中间件使用教程