NetCore Swagger 多版本

  • NetCore Swagger 多版本已关闭评论
  • 193 次浏览
  • A+
所属分类:.NET技术
摘要

 NetCore 配置Swagger  


1.版本枚举

    /// <summary>     /// swagger 多版本枚举     /// </summary>     public enum SwaggerVersionEnum     {         /// <summary>         /// V1 版本,复杂情况可通过特性获取         /// </summary>         [Description("V1.000")]         V1 = 1000,         /// <summary>         /// V2 版本,复杂情况可通过特性获取         /// </summary>         [Description("V2.000")]         V2 = 2000,         /// <summary>         /// V2 版本,复杂情况可通过特性获取         /// </summary>         [Description("V3.000")]         V3 = 3000,     }

2.自定义特性,重写路由

using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApiExplorer; using System;      /// <summary>     /// 自定义路由 /api/{version}/[controler]/[action]     /// </summary>     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]     public class SwaggerVersionAttribute : RouteAttribute, IApiDescriptionGroupNameProvider     {         /// <summary>         /// 分组名称,是来实现接口 IApiDescriptionGroupNameProvider         /// </summary>         public string GroupName { get; set; }          /// <summary>         /// 自定义路由构造函数,继承基类路由         /// </summary>         /// <param name="actionName"></param>         public SwaggerVersionAttribute(string actionName = "[action]") : base("/api/{version}/[controller]/" + actionName)         {         }         /// <summary>         /// 自定义版本+路由构造函数,继承基类路由         /// </summary>         /// <param name="actionName"></param>         /// <param name="version"></param>         public SwaggerVersionAttribute(SwaggerVersionEnum version, string actionName = "[action]") : base($"/api/{version.GetDescription()}/[controller]/{actionName}")         {             GroupName = version.GetDescription();         }     }

3.接口使用特性

        /// <summary>         /// add2         /// </summary>         /// <param name="dto"></param>         /// <returns></returns>         [HttpPost, SwaggerVersion(SwaggerVersionEnum.V2, "add")]         public async Task<int> V2_Add([FromBody] ProductDto dto)         {             await Task.Run(() => { });             return 1;         }

5.修改swagger配置

        /// <summary>         /// 添加服务: swagger         /// </summary>         /// <param name="services"></param>         /// <returns></returns>         public static void AddCustSwagger(this IServiceCollection services)         {             var version = "V1.0";             var apiName = "XXX系统";             //  swagger多版本配置             var basePath = Directory.GetCurrentDirectory();             services.AddSwaggerGen(c =>             {                 //var versionList = typeof(SwaggerVersionEnum).GetEnumNames();                 var versionList = EnumExtend.GetEnumList<SwaggerVersionEnum>().Select(x => x.Description);                 versionList.ToList().ForEach(version =>                 {                     c.SwaggerDoc(version, new OpenApiInfo//"V1"                     {                         Version = version,                         Title = $"{apiName} 接口文档",                         Description = $"{apiName} HTTP API {version}",                         //Contact = new OpenApiContact { Name = apiName, Email = "swagger@xxx.com", Url = new Uri("https://www.cnblogs.com/CRobot/") },                         //License = new OpenApiLicense { Name = apiName, Url = new Uri("https://www.cnblogs.com/CRobot/") }                     });                     c.OrderActionsBy(o => o.RelativePath);                      //  获取应用程序xml所在目录                     var xmlPath = Path.Combine(basePath, "ProjectName.xml");                     //  swagger界面默认只显示 方法&字段 注释,不显示 控制器注释                     //  第二个参数为true, 则是controller的注释                     c.IncludeXmlComments(xmlPath, true);                 });             });         }          /// <summary>         /// 添加中间件: swagger         /// </summary>         /// <param name="app"></param>         public static void UseCustSwagger(this IApplicationBuilder app)         {             app.UseSwagger();             app.UseSwaggerUI(options =>             {                 //  swagger多版本配置                 var apiName = "XXX系统";                 //根据版本名称倒序 遍历展示                 //var versionList = typeof(SwaggerVersionEnum).GetEnumNames();                 var versionList = EnumExtend.GetEnumList<SwaggerVersionEnum>().Select(x => x.Description);                 versionList.OrderByDescending(e => e).ToList().ForEach(version =>                 {                     options.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{apiName} {version}");                 });                 //  默认路径为:/swagger/index.html                 //  路由前缀 - 设置为空,可直接跳转到swagger页面:/index.html                 //  api测试可设置为空,部署时容易与前端路由冲突                 options.RoutePrefix = string.Empty;             });         }

 

Reference:

NetCore 配置Swagger