如何在NetCore8.0 Swagger 里配置多版本

话不多说 ,先看效果

要做成以上效果也不难。请跟好脚步,下面带你们一步一步来做
首先要新建一个类 ApiVersionInfo

 public class ApiVersionInfo
 {
     

     /// <summary>
     /// 获取或者设置 V1 版本。
     /// </summary>
     public static string 软件版本 = "V1";

     /// <summary>
     /// 获取或者设置 V2 版本。
     /// </summary>
     public static string 小程序版本 = "V2";

     /// <summary>
     /// 获取或者设置 V3 版本。
     /// </summary>
     public static string 其它版 = "V3";

     /// <summary>
     /// 获取或者设置 V4 版本。
     /// </summary>
 
 }

然后去 Program.cs 配置 Swagger 两个地方 
1. 在 add swagger  这里 代码如下
 

builder.Services.AddSwaggerGen(optin =>
{
    
    #region  1. 配置Swagge 本版
    foreach (FieldInfo field in typeof(ApiVersionInfo).GetFields())
    {
        optin.SwaggerDoc(field.Name, new Microsoft.OpenApi.Models.OpenApiInfo()
        {
           
            Title = $"{field.GetValue(typeof(ApiVersionInfo))}",
            Version = field.Name,
            Description = $"当前 API {field.Name}"
        });
    };
    #endregion


});

2. 在 UseSwaggerUI 这里 代码如下
 

 app.UseSwaggerUI(option => 
 {
     #region 2. Swagger 具体的配置
     foreach (FieldInfo field in typeof(ApiVersionInfo).GetFields())
     {
         option.SwaggerEndpoint($"/swagger/{field.Name}/swagger.json", $"{field.Name}");
     }

     #endregion

 });

3.配完后 就可以在控制器里用了 

在要用的控制器上加上 以下特性

  [ApiExplorerSettings(GroupName = nameof(ApiVersionInfo.小程序版本))]

可以看以下图片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值