• 在ASP.Net Core Web API中使用Swagger进行版本控制


    使用过程参考:在ASP.Net Core Web API中使用Swagger,本文在此基础上阐述如何进行API文档的版本控制。

    1、添加API枚举类型

    public enum ApiVersion
    {
        /// <summary>
        /// v1版本
        /// </summary>
        V1 = 1,
        /// <summary>
        /// v2版本
        /// </summary>
        V2 = 2
    }

     2、注册Swagger服务

    public void ConfigureServices(IServiceCollection services)
    {
        #region 注册Swagger服务
        services.AddSwaggerGen(options =>
        {
            typeof(ApiVersion).GetEnumNames().ToList().ForEach(version =>
            {
                options.SwaggerDoc(version, new OpenApiInfo()
                {
                    Version = version,
                    Title = $"webapi {version}",
                    Description = $"Asp.NetCore Web API {version}"
                });
            });
        });
        #endregion
    
        services.AddControllers();
    }

     3、启用Swagger

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
       if
    (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //启用Swagger中间件 app.UseSwagger(); app.UseSwaggerUI(options => { typeof(ApiVersion).GetEnumNames().ToList().ForEach(version => { options.SwaggerEndpoint($"/swagger/{version}/swagger.json", version); }); }); app.UseRouting();
       app.UseAuthorization(); app.UseEndpoints(endpoints
    => { endpoints.MapControllers(); }); }

     4、在控制器中使用ApiExplorerSettings标记

    namespace WebApi.Controllers.V1
    {
        [Route("api/v1/[controller]")]
        [ApiExplorerSettings(GroupName = "V1")]
        [ApiController]
        public class TestController : ControllerBase
        {
            [HttpGet]
            [Route("Get")]
            public string Get()
            {
                return "123456 v1";
            }
        }
    }
    namespace WebApi.Controllers.V2
    {
        [Route("api/v2/[controller]")]
        [ApiExplorerSettings(GroupName = "V2")]
        [ApiController]
        public class TestController : ControllerBase
        {
            [HttpGet]
            [Route("Get")]
            public string Get()
            {
                return "123456 v2";
            }
        }
    }

    5、注意事项

    (1) 在控制器中使用ApiExplorerSettings标记时,GroupName的值要和ApiVersion中的枚举名称一致,否则Swagger列出的API版本列表不会有该控制器的API,导致Swagger网页中该控制器API文档不会出现。

    (2) 枚举类型ApiVersion不是必须的,只是用它来获取版本列表,例如可以使用new List<string>() { "V1", "V2" }.ForEach代替typeof(ApiVersion).GetEnumNames().ToList().ForEach。

     6、运行效果

  • 相关阅读:
    解决方案solution
    Marshal类
    鼠标钩子WH_MOUSE_LL和WH_MOUSE的区别
    DllImport
    打包.py文件成.exe
    C++定义全部变量注意项
    类.cpp文件不识别类.h所定义的结构体问题
    C++判断文件是否存在
    博客专栏
    软件测试基础知识
  • 原文地址:https://www.cnblogs.com/xhubobo/p/14445511.html
Copyright © 2020-2023  润新知