一、.NET6中使用swagger
swagger支持 API 自动生成同步的在线文档,下面在.NET6中引入
1.建.NET6应用并建以下控制器
////// 订单接口 /// [ApiController] [Route("[controller]/[action]")] public class OrderController : Controller { /// /// 获取订单 /// /// [HttpGet] public string GetOrder() { return "ok"; } /// /// 创建订单 /// /// 订单信息 /// [HttpPost] public string CreateOrder([FromBody] OrderRequest request) { return "ok"; } /// /// 删除订单 /// /// [HttpDelete] public string DeleteOrder() { return "ok"; } /// /// 更新订单 /// /// [HttpPut] public string UpdateOrder() { return "ok"; } }
////// 订单请求 /// public class OrderRequest { /// /// 订单名称 /// public string orderName { get; set; } /// /// 订单编号 /// public string orderNo { get; set; } /// /// 价格 /// public decimal price { get; set; } }
2.Nuget包安装swagger需要dll
Swashbuckle.AspNetCore
3.Program.cs中加入swagger
using Microsoft.OpenApi.Models; using System.Reflection; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); builder.Services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "API标题", Description = "API描述" }); }); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
这时候访问 http://localhost:xxx/swagger/index.html 已经能访问和显示接口了,但是少了注释
4.生成xml文件,接口文档生成注释需要程序集的xml文件
打开项目的.csproj文件加上标识让程序生成这个程序集的文档
true
5.在Program.cs处加上加载这个xml文件
完成的 Program.cs文件
using Microsoft.OpenApi.Models; using System.Reflection; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); builder.Services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "API标题", Description = "API描述" }); var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename)); }); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
这时再运行就能看到注释了
注意:如果参数的Model在其它类库,那么所引用的类库的.csproj文件也要加上上面的标识,并在Program.cs引入程序集的xml文件才能展示参数的注释。
二、.NET6中使用swagger版本控制
1.增加文件 ApiVerionInfo.cs记录版本号
////// api版本号 /// public class ApiVersionInfo { public static string V1; public static string V2; public static string V3; public static string V4; public static string V5; }
2.在api控制器上增加版本
[ApiExplorerSettings(GroupName =nameof(ApiVersionInfo.V1))]
3.再建一个控制器,写v2版本的接口
////// 订单接口 /// [ApiController] [Route("[controller]/[action]")] [ApiExplorerSettings(GroupName = nameof(ApiVersionInfo.V2))] public class OrderV2Controller : Controller { /// /// 获取订单 /// /// [HttpGet] public string GetOrder() { return "ok"; } /// /// 创建订单 /// /// 订单信息 /// [HttpPost] public string CreateOrder([FromBody] OrderRequest request) { return "ok"; } }
4.Program.cs中swagger的引入
完整配置:
using Microsoft.OpenApi.Models; using Swagger.Demo; using System.Reflection; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); builder.Services.AddSwaggerGen(options => { foreach (FieldInfo fileld in typeof(ApiVersionInfo).GetFields()) { options.SwaggerDoc(fileld.Name, new OpenApiInfo { Version = fileld.Name, Title = "API标题", Description = $"API描述,{fileld.Name}版本" }); } var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename)); }); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(c => { foreach (FieldInfo field in typeof(ApiVersionInfo).GetFields()) { c.SwaggerEndpoint($"/swagger/{field.Name}/swagger.json", $"{field.Name}"); } }); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
5.配置完成,查看效果
到这里版本控制就完成了!