net5 webapi中 SwaggerUI如何进行版本控制

2023-10-21 18:37:53 浏览数 (2)

创建项目

net5就自带上了swaggerUI,见红色

代码语言:javascript复制
     // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "Net5.WebAPI", Version = "v1" });
            });
        }

        // 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();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Net5.WebAPI v1"));
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

代码改造

1.添加FirstController

代码语言:javascript复制
   public class FirstController : ControllerBase
    {
        /// <summary>
        /// 这是V1版本的GetString
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string GetToString()
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                Id = 123,
                Name = "闪电五连鞭"
            });
        }


        /// <summary>
        /// 这是V1版本的Add
        /// </summary>
        /// <returns>name</returns>
        [HttpPost]
        public string Add(string name)
        {
            return JsonConvert.SerializeObject(new
            {
                Id = 234,
                Name = name
            });
        }

        [HttpPut]
        public int Update(int Id)
        {
            return Id;
        }
        [HttpDelete]
        public int Delete(int Id)
        {
            return Id;
        }

        [HttpPatch]
        public int Patch()
        {
            return 123;
        }
    }

新建文件夹V2, 放入新版本的代码

代码语言:javascript复制
    [Route("api/[controller]")]
    [ApiController]
    public class FirstController : ControllerBase
    {
        /// <summary>
        /// 这是V2版本的GetString
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string GetToString()
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                Id = 123,
                Name = "闪电五连鞭"
            });
        }


        /// <summary>
        /// 这是V2版本的Add
        /// </summary>
        /// <returns>name</returns>
        [HttpPost]
        public string Add(string name)
        {
            return JsonConvert.SerializeObject(new
            {
                Id = 234,
                Name = name
            });
        }

        [HttpPut]
        public int Update(int Id)
        {
            return Id;
        }
        [HttpDelete]
        public int Delete(int Id)
        {
            return Id;
        }

        [HttpPatch]
        public int Patch()
        {
            return 123;
        }
    }

2.生成swagge有关项目的Xml注释文件,并修改其属性为“始终复制”

 3.添加版本枚举类

代码语言:javascript复制
 public enum ApiVersions
        {
            V1 = 1,
            V2 = 2,
            V3 = 3,
            V4 = 4,
            V5 = 5
        }

4.改造StartUp中swagger代码

代码语言:javascript复制
     public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
                {
                    c.SwaggerDoc(version, new OpenApiInfo()
                    {
                        Title = "Net5.WebAPI",
                        Version = version,
                        Description = $"Net5.WebAPI的 {version} 版本,可根据需要选择"
                    });
                });

                #region 为Swagger JSON and UI设置xml文档注释路径 
                string basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
                string xmlPath = Path.Combine(basePath, "Net5.WebAPI.xml");

                c.IncludeXmlComments(xmlPath);
                #endregion

                // c.SwaggerDoc("v1", new OpenApiInfo { Title = "Net5.WebAPI", Version = "v1" });
            });
        }

        // 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();
                app.UseSwaggerUI(c =>
                {
                    typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
                    {
                        c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"Net5.WebAPI {version}");
                    });
                    //c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Net5.WebAPI v1")
                });
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

添加版本号

在需要进行版本控制的控制器添加版本  [ApiExplorerSettings(GroupName = "V?")]   [Route("api/V?/[controller]")]

 大功告成,运行效果如下

 源码下载

进下面的QQ群,在群在线文档里面

0 人点赞