Net7中对Swagger增加AuthToken和版本控制

发布时间 2023-08-14 15:15:57作者: 王月半子

首先贴上版本控制枚举

    /// <summary>
    /// Api版本枚举
    /// </summary>
    public enum ApiVersions
    {
        V1,
        V2,
        V3,
        V4
    }

怎么使用呢,在选中的Controller上贴上特性即可

    [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]

SwaggerGen中配置

 /// <summary>
 /// 配置Swagger
 /// </summary>
 /// <param name="services"></param>
 public static void AddSwaggerExt(this IServiceCollection services, string docName, string docDescription)
 {
     services.AddEndpointsApiExplorer();
     services.AddSwaggerGen(option =>
     {
         foreach (var version in typeof(ApiVersions).GetEnumNames())
         {
             option.SwaggerDoc(version, new OpenApiInfo()
             {
                 Title = !string.IsNullOrWhiteSpace(docName) ? docName : $"Swagger的Api文档",
                 Version = version,
                 Description = !string.IsNullOrWhiteSpace(docDescription) ? docDescription : $"通用版本的CoreApi版本v1"
             });
         }

         // xml文档绝对路径 
         var file = Path.Combine(AppContext.BaseDirectory, $"{AppDomain.CurrentDomain.FriendlyName}.xml");

         // true : 显示控制器层注释
         option.IncludeXmlComments(file, true);
         // 对action的名称进行排序,如果有多个,就可以看见效果了。
         option.OrderActionsBy(o => o.RelativePath);

         //添加安全定义--配置支持token授权机制
         option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
         {
             Description = "请输入token,格式为 Bearer xxxxxxxx(注意中间必须有空格)",
             Name = "Authorization",
             In = ParameterLocation.Header,
             Type = SecuritySchemeType.ApiKey,
             BearerFormat = "JWT",
             Scheme = "Bearer"
         });
         //添加安全要求
         option.AddSecurityRequirement(new OpenApiSecurityRequirement
         {
           {
                 new OpenApiSecurityScheme
                 {
                     Reference =new OpenApiReference()
                     {
                         Type = ReferenceType.SecurityScheme,
                         Id ="Bearer"
                     }
                 },
                 new string[]{ }
             }
         });
     });
 }

UI配置,这个之前说过了,这里只是重复贴一下,和上面的关系不大

/// <summary>
/// 使用Swagger
/// </summary>
/// <param name="app"></param>
public static void UseSwaggerExt(this WebApplication app, string docName)
{
    app.UseSwagger();
    app.UseSwaggerUI(option =>
    {
        foreach (string version in typeof(ApiVersions).GetEnumNames())
        {
            option.SwaggerEndpoint($"/swagger/{version}/swagger.json", string.IsNullOrWhiteSpace(docName) ? docName : $"Steven文档【{version}】版本");
        }
    });
}