NetCore 使用 Swagger - 版本控制
第一步:创建版本枚举类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /// <summary> /// Api版本枚举类 /// </summary> public enum ApiVersions { /// <summary> /// 版本V1 /// </summary> V1 = 1, /// <summary> /// 版本V2 /// </summary> V2 = 2 } |
第二步:Program.cs 注册服务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen(options => { // 注释 var xmlFilename = $ "{Assembly.GetExecutingAssembly().GetName().Name}.xml" ; // 第二个参数为是否显示控制器注释,我们选择true options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename), true ); // 生成多个文档显示 typeof (ApiVersions).GetEnumNames().ToList().ForEach(version => { //添加文档介绍 options.SwaggerDoc(version, new OpenApiInfo { Title = $ "项目名" , Version = version, Description = $ "项目名:{version}版本" }); }); }); |
Program.cs 使用服务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(options => { //options.SwaggerEndpoint($"/swagger/V1/swagger.json", $"版本选择:V1"); //如果只有一个版本也要和上方保持一致 typeof (ApiVersions).GetEnumNames().ToList().ForEach(version => { //切换版本操作 //参数一是使用的哪个json文件,参数二就是个名字 options.SwaggerEndpoint($ "/swagger/{version}/swagger.json" , $ "版本选择:{version}" ); }); }); } |
第三步:创建控制器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | namespace WebApiVer.Controllers { [ApiController] [Route( "api/[controller]/[action]" )] [Produces( "application/json" )] public class TestController : ControllerBase { /// <summary> /// 获取授权的token /// </summary> [HttpPost( "/Test/" + nameof(ApiVersions.V1) + "/Login" )] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ApiExplorerSettings(GroupName = nameof(ApiVersions.V1))] //下面这个语法在netcore6.0已经无效了 //[ApiVersion("V1",Deprecated =true)] public IActionResult Login_V1() { return Ok( new { code = 200, message = "登录成功" }); } [HttpPost( "/Test/" + nameof(ApiVersions.V2) + "/Login" )] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] [ApiExplorerSettings(GroupName = nameof(ApiVersions.V2))] public IActionResult Login_V2() { return Ok( new { code = 200, message = "登录成功" }); } /// <summary> /// 如果不标识版本,那么这个函数出现在任何一个版本中 /// </summary> [HttpPost] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status401Unauthorized)] public IActionResult Logout() { //return new UnauthorizedResult(); return Ok( new { code = 200, message = "登录成功" }); } } } |
第四步:设置项目属性
第五步:最终效果
分类:
Asp.Net Core
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?