Net7中对Swagger增加AuthToken和版本控制
首先贴上版本控制枚举
/// <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}】版本"); } }); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!