.NetCore WebApi —— Swagger版本控制

上接:.NetCore WebApi——基于JWT的简单身份认证与授权(Swagger)

版本控制的好处是显而易见的,利用Swagger展示不同版本的API更能体现效果。

1.安装Nuget包:Microsoft.AspNetCore.Mvc.Versioning

2. 配置Startup类

 2.1  添加新成员 ,用来获取API版本信息

     /// <summary>
        /// Api版本信息
        /// </summary>
        private IApiVersionDescriptionProvider provider;

 2.2 在 ConfigureServices 方法中注册服务

services.AddApiVersioning(option =>
            {
                // 可选,为true时API返回支持的版本信息
                option.ReportApiVersions = true;
                // 不提供版本时,默认为1.0
                option.AssumeDefaultVersionWhenUnspecified = true;
                // 请求中未指定版本时默认为1.0
                option.DefaultApiVersion = new ApiVersion(1, 0);
            }).AddVersionedApiExplorer(option =>
            {
          // 版本名的格式:v+版本号 option.GroupNameFormat
= "'v'V"; option.AssumeDefaultVersionWhenUnspecified = true; }); this.provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>();

 2.3 遍历API版本信息,在原有的AddSwaggerGen方法中循环处理:红色部分

           // 注册Swagger服务
            services.AddSwaggerGen(c =>
            {
                // 多版本控制
                foreach (var item in provider.ApiVersionDescriptions)
                {
                    // 添加文档信息
                    c.SwaggerDoc(item.GroupName, new Info
                    {
                        Title = "CoreWebApi",
                        Version = item.ApiVersion.ToString(),
                        Description = "ASP.NET CORE WebApi",
                        Contact = new Contact
                        {
                            Name = "Jee",
                            Email = "[email protected]",
                            Url = "https://www.cnblogs.com/jixiaosa/"
                        }
                    });
                }
                

2.4 修改 Configure 方法中的 SwaggerUI方法,同样做循环处理

       // 配置SwaggerUI
            app.UseSwaggerUI(c =>
            {
                foreach (var item in provider.ApiVersionDescriptions)
                {
                    //c.SwaggerEndpoint("/swagger/v1/swagger.json", "CoreAPI"); 单版本
                    c.SwaggerEndpoint($"/swagger/{item.GroupName}/swagger.json", "CoreAPI"+item.ApiVersion);
                }
                c.RoutePrefix = string.Empty;
            });

2.5 在控制器中应用

 2.5.1 在Test控制器中添加特性标签以及路由。 1.0版本

2.5.1 在Value控制器中添加特性标签以及路由。 2.0版本

3. 启动项目查看效

Gif

github:   https://github.com/xiaoMaPrincess/Asp.NetCore-WebApi

多层架构版本:https://github.com/xiaoMaPrincess/.NetCoreWebApi

猜你喜欢

转载自www.cnblogs.com/jixiaosa/p/10817143.html