利用swagger和API Version实现api版本控制
场景:
在利用.net core进行api接口开发时,经常会因为需求,要开发实现统一功能的多版本的接口。比如版本V1是给之前用户使用,然后新用户有新需求,这时候可以单独给这个用户写接口,也可以在V1基础上写版本V2,这样V1的用户要使用V2的接口,只有稍微改一下就可以了。
实现:
1.APIVersion
首先需要安装Nuget包:Microsoft.AspNetCore.Mvc.Versioning 以及 Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer
然后在ConfigureServices中添加以下内容;
1 // API接口版本 2 services.AddApiVersioning(o => { 3 o.ReportApiVersions = true; 4 o.AssumeDefaultVersionWhenUnspecified = true; 5 //o.ApiVersionReader = new HeaderApiVersionReader("version"); 6 o.DefaultApiVersion = new ApiVersion(1, 0); 7 }); 8 services.AddVersionedApiExplorer( o => { 9 o.GroupNameFormat = "'v'VVV"; 10 o.SubstituteApiVersionInUrl = true; 11 });
同时在Configure中添加以下内容:
app.UseApiVersioning();
ApiVersion用来配置默认版本,版本位置等,这里的ApiVersionReader可以设定api版本位置,比如是http中的Header位置,还是放在请求中。
VersionedApiExplorer用来版本管理,其中的GroupNameFormat是api组名格式,而SubstituteApiVersionInUrl 是设置在url中替换版本
之后在控制器上添加版本,如下:
/// <summary> /// 角色相关 /// </summary> [ApiVersion("2.0")] [TypeFilter(typeof(AuthFilter))] [ApiController] [Route("api/v{version:apiVersion}/[controller]/[action]")] public class RoleController:ControllerBase { /// <summary> /// 添加角色,版本2 /// </summary> /// <param name="req"></param> /// <returns></returns> [HttpPost,MapToApiVersion("2.0")] public Response<DTO_Id> AddRole(DTO_AddOrUpdate_Role_V2 req) { } }
/// <summary> /// 角色相关,版本1 /// </summary> [ApiVersion("1.0")] [TypeFilter(typeof(AuthFilter))] [ApiController] [Route("api/v{version:apiVersion}/[controller]/[action]")] public class RoleController:ControllerBase { /// <summary> /// 添加角色 /// </summary> /// <param name="req"></param> /// <returns></returns> [HttpPost] public Response<DTO_Id> AddRole(DTO_AddOrUpdate_Role req) { } }
这里在apiVersion中设置控制器版本,同时可以通过参数不同来重载函数。这样就实现了版本控制
2.swagger
首先先导入nuget包,Swashbuckle.AspNetCore
在ConfigureService中配置swaager,如下;
var provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>(); // swagger services.AddSwaggerGen(c => { // 排序方式 c.OrderActionsBy(o => o.HttpMethod); foreach (var item in provider.ApiVersionDescriptions) { c.SwaggerDoc(item.GroupName, new OpenApiInfo { Title = "WebAPI" + item.GroupName, Version = item.ApiVersion.MajorVersion.ToString() + "." + item.ApiVersion.MinorVersion }); } c.OperationFilter<GlobalHttpHeaderOperationFilter>(); // 重载方式 c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); foreach (var name in Directory.GetFiles(AppContext.BaseDirectory, "*.*", SearchOption.AllDirectories).Where(f => Path.GetExtension(f).ToLower() == ".xml")) { c.IncludeXmlComments(name, includeControllerXmlComments: true); } });
这里需要获取APIversion中各个版本的信息,可以利用services.BuildServiceProvider().GetRequiredService<>获取。
c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
同时这句是为了让swaager支持函数重载。而且可以通过OrderActionsBy来设置排序顺序。
最后在Configure中使用swagger。
app.UseSwagger(); var provider = _services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>(); app.UseSwaggerUI(c => { foreach (var item in provider.ApiVersionDescriptions) { c.SwaggerEndpoint($"/swagger/{item.GroupName}/swagger.json", item.GroupName); } });
为了获取serviceCollection中的apiversion信息,需要添加如下;
private IServiceCollection _services;
在ConfigureServices中添加:
_services = services;
这样就能在Configure中使用ServiceCollention中的service了。
结果:
可以通过swagger中的definition来选择接口版本,也能看到接口版本显示先url中。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)