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

明志德道發表於2021-03-07

建立專案

net5就自帶上了swaggerUI,見紅色

     // 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

   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, 放入新版本的程式碼

    [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.新增版本列舉類

 public enum ApiVersions
        {
            V1 = 1,
            V2 = 2,
            V3 = 3,
            V4 = 4,
            V5 = 5
        }

4.改造StartUp中swagger程式碼

     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群,在群線上文件裡面

相關文章