NetCore 版本控制

发布时间 2024-01-09 09:01:58作者: microsoft-zhcn

第一步:创建版本枚举类

/// <summary>
/// Api版本枚举类
/// </summary>
public enum ApiVersions
{
    /// <summary>
    /// 版本V1
    /// </summary>
    V1 = 1,
    /// <summary>
    /// 版本V2
    /// </summary>
    V2 = 2
}

 第二步:Program.cs 注册服务

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 使用服务

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}");
        });
    });
}

 第三步:创建控制器

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 = "登录成功"
            });
        }
    }
}

 最终效果: