asp.net core 3.0中使用swagger的方法与问题
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
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对我们的支持。
栏 目:ASP.NET
本文标题:asp.net core 3.0中使用swagger的方法与问题
本文地址:https://www.xiuzhanwang.com/a1/ASP_NET/10852.html
您可能感兴趣的文章
- 01-11如何给asp.net core写个简单的健康检查
- 01-11浅析.Net Core中Json配置的自动更新
- 01-11.net core高吞吐远程方法如何调用组件XRPC详解
- 01-11.NET Core 迁移躺坑记续集之Win下莫名其妙的超时
- 01-11docker部署Asp.net core应用的完整步骤
- 01-11.net core webapi jwt 更为清爽的认证详解
- 01-11ASP.NET Core静态文件的使用方法
- 01-11.NET Core 3.0之创建基于Consul的Configuration扩展组件
- 01-11.net core EF Core调用存储过程的方式
- 01-11asp.net Core3.0区域与路由配置的方法
阅读排行
本栏相关
- 01-11vscode extension插件开发详解
- 01-11VsCode插件开发之插件初步通信的方法
- 01-11如何给asp.net core写个简单的健康检查
- 01-11.net core高吞吐远程方法如何调用组件
- 01-11浅析.Net Core中Json配置的自动更新
- 01-11.NET开发人员关于ML.NET的入门学习
- 01-11.NET Core 迁移躺坑记续集之Win下莫名其
- 01-11.net core webapi jwt 更为清爽的认证详解
- 01-11docker部署Asp.net core应用的完整步骤
- 01-11ASP.NET Core静态文件的使用方法
随机阅读
- 08-05织梦dedecms什么时候用栏目交叉功能?
- 01-10delphi制作wav文件的方法
- 01-11ajax实现页面的局部加载
- 08-05DEDE织梦data目录下的sessions文件夹有什
- 01-10SublimeText编译C开发环境设置
- 01-10使用C语言求解扑克牌的顺子及n个骰子
- 01-11Mac OSX 打开原生自带读写NTFS功能(图文
- 04-02jquery与jsp,用jquery
- 01-10C#中split用法实例总结
- 08-05dedecms(织梦)副栏目数量限制代码修改