Intro#
上次更新了 asp.net core 3.0 简单的记录了一下 swagger 的使用,那个项目的 api 比较简单,都是匿名接口不涉及到认证以及 api 版本控制,最近把另外一个 api 项目升级到了 3.0,还是遇到了一些问题,这里单独写一篇文章介绍,避免踩坑。
Swagger 基本使用#
swagger 服务注册:
services.AddSwaggerGen(option => { option.SwaggerDoc("sparktodo", new OpenApiInfo { Version = "v1", Title = "SparkTodo API", Description = "API for SparkTodo", Contact = new OpenApiContact() { Name = "WeihanLi", Email = "weihanli@outlook.com" } }); // include document file option.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{typeof(Startup).Assembly.GetName().Name}.xml"), true); });
中间件配置:
//Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); //Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint app.UseSwaggerUI(option => { option.SwaggerEndpoint("/swagger/sparktodo/swagger.json", "sparktodo Docs"); option.RoutePrefix = string.Empty; option.DocumentTitle = "SparkTodo API"; });
为 Swagger 添加 Bearer Token 认证#
services.AddSwaggerGen(option => { // ... // Add security definitions option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() { Description = "Please enter into field the word 'Bearer' followed by a space and the JWT value", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, }); option.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference() { Id = "Bearer", Type = ReferenceType.SecurityScheme } }, Array.Empty<string>() } }); });
支持多个 ApiVersion#
services.AddApiVersioning(options => { options.AssumeDefaultVersionWhenUnspecified = true; options.DefaultApiVersion = ApiVersion.Default; options.ReportApiVersions = true; }); services.AddSwaggerGen(option => { // ... option.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "API V1" }); option.SwaggerDoc("v2", new OpenApiInfo { Version = "v2", Title = "API V2" }); option.DocInclusionPredicate((docName, apiDesc) => { var versions = apiDesc.CustomAttributes() .OfType<ApiVersionAttribute>() .SelectMany(attr => attr.Versions); return versions.Any(v => $"v{v.ToString()}" == docName); }); option.OperationFilter<RemoveVersionParameterOperationFilter>(); option.DocumentFilter<SetVersionInPathDocumentFilter>(); });
自定义 Api version 相关的 OperationFilter:
public class SetVersionInPathDocumentFilter : IDocumentFilter { public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { var updatedPaths = new OpenApiPaths(); foreach (var entry in swaggerDoc.Paths) { updatedPaths.Add( entry.Key.Replace("v{version}", swaggerDoc.Info.Version), entry.Value); } swaggerDoc.Paths = updatedPaths; } } public class RemoveVersionParameterOperationFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { // Remove version parameter from all Operations var versionParameter = operation.Parameters.Single(p => p.Name == "version"); operation.Parameters.Remove(versionParameter); } }
中间件配置:
//Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); //Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint app.UseSwaggerUI(option => { option.SwaggerEndpoint("/swagger/v2/swagger.json", "V2 Docs"); option.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs"); option.RoutePrefix = string.Empty; option.DocumentTitle = "SparkTodo API"; });
最终 swagger 效果
Memo#
上面的配置来自 https://github.com/WeihanLi/SparkTodo 这个项目,要获取代码可以参考这个项目
Reference#
- https://github.com/domaindrivendev/Swashbuckle.AspNetCore/tree/master/test/WebSites/MultipleVersions/Swagger
- https://stackoverflow.com/questions/58197244/swaggerui-with-netcore-3-0-bearer-token-authorization
- https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1295
- https://github.com/WeihanLi/SparkTodo
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。