asp.net core 3.0 中使用 swagger

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 效果

640?wx_fmt=png

640?wx_fmt=png

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/313309.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

由微软100题“求和不用for while”引出的static类成员的知识

转自&#xff1a;http://www.cnblogs.com/gysm/archive/2011/09/16/2179277.html C类中谈到static,我们可以在类中定义static成员&#xff0c;static成员函数&#xff01;Cprimer里面讲过&#xff1a;static成员它不像普通的数据成员&#xff0c;static数据成员独立于该类的任意…

MCN是啥?了解一下这5个互联网热词

骗子刷量&#xff0c;黑吃黑半斤八两前几天一件事火爆了互联网圈&#xff0c;一场搞笑的骗局&#xff0c;一场蜂群传媒导演的“僵尸舞台剧”&#xff1a;一条一夜爆红的视频 流量却为0&#xff01;。一个电商商家卖产品有投放需求&#xff0c;找到了微博上一家 MCN 机构的一个女…

Matlab出现On Startup: Error using eval undefined function 'workspacefunc' for input arguments of type

按照提示 Warning: MATLAB did not appear to successfully set the search path. To recover for this session of MATLAB, type "restoredefaultpath;matlabrc". To find out how to avoid this warning the next time you start MATLAB, type "docsearch pr…

为什么我不建议你去外包公司?

前言在我离开上家公司之前&#xff0c;我的直属领导找我聊了一番。除了问候我有没有找好下家之外&#xff0c;还千叮咛万嘱咐我千万不要去外包公司&#xff0c;否则会在简历上留下无法磨灭的污点。当时的我对于外包公司的了解并不深&#xff0c;只是道听途说外包公司很坑&#…

x 的平方根

题目描述 实现 int sqrt(int x) 函数。 计算并返回 x 的平方根&#xff0c;其中 x 是非负整数。 由于返回类型是整数&#xff0c;结果只保留整数的部分&#xff0c;小数部分将被舍去。 示例 1: 输入: 4 输出: 2示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由…

Caffe编译代码的时候报各种未定义未声明

自己装的CUDNN是一个版本&#xff0c;而运行别人的code时可能人家对应CUDNN的另一个版本&#xff0c;此时需要修改关键字来兼容版本&#xff0c;参考 1. https://github.com/BVLC/caffe/issues/1792 https://github.com/BVLC/caffe/pull/1739 https://github.com/BVLC/ca…

友浩达优选上新,原生态农产品,买得安心,吃得放心

大闸蟹还在热卖&#xff0c;需要的同学可以访问 各位一直支持队长的朋友们友浩达优选上新了本着为大家推荐好东西的想法商城里上架的商品都是队长亲自挑选有质量保证的口碑好商品这次&#xff0c;来看看队长又给大家带了哪些好东西本次上新全是各地优选原生态农产品食品优质、安…

判别学习与生成学习的区别

参照http://blog.csdn.net/daijiguo/article/details/52218207 比如二类分类问题&#xff0c;不管是感知器算法还是逻辑斯蒂回归算法&#xff0c;都是在解空间中寻找一条直线从而把两种类别的样例分开&#xff0c;对于新的样例只要判断在直线的哪一侧即可&#xff1b;这种直接对…

树莓派4上跑 .NET Core 3.0,这次,真·64位!

导语前不久我写了一篇《Gentoo由于 Windows 10 IoT Core &#xff08;以及上面的UWP们&#xff09;暴尸荒野而苟且偷生使用 Linux 的我&#xff0c;已经彻底开荤了。最近我发现有个叫 Gentoo 的 Linux 系统&#xff0c;支持树莓派4的64位CPU。项目地址&#xff1a;https://gith…

微软100题第20题

http://blog.csdn.net/zwb8848happy/article/details/7340634 输入一个表示整数的字符串&#xff0c;把该字符串转换成整数并输出 //Analysis: //1. Whether it is a negative number //2. Whether there exist other characters that do not represent numbers //#includ…

asp.net core 使用 AccessControlHelper 控制访问权限

asp.net core 使用 AccessControlHelper 控制访问权限Intro由于项目需要&#xff0c;需要在基于 asp.net mvc 的 Web 项目框架中做权限的控制&#xff0c;于是才有了这个权限控制组件&#xff0c;最初只是支持 netframework&#xff0c;后来 dotnetcore 2.0 发布了之后添加了对…

Caffe 增加自定义 Layer 及其 ProtoBuffer 参数

转载自&#xff1a;http://blog.csdn.net/kkk584520/article/details/52721838 http://blog.csdn.net/kkk584520 博客内容基于新书《深度学习&#xff1a;21 天实战 Caffe》&#xff0c;书中课后习题答案欢迎读者留言讨论。以下进入正文。 在使用 Caffe 过程中经常会有这样的…

.NET Core 3.0愈加成熟,微软将不再把.NET Framework API移植给它

目前 .NET Core 3.0 拥有的 API 总数约为 .NET Framework API 的 80%&#xff0c;剩下尚未从 .NET Framework 移植到 .NET Core 的 API&#xff0c;微软考虑以开源的形式发布。微软方面表示&#xff0c;通过 .NET Core 3.0&#xff0c;他们现在已具备轻松移植现代 workload 所需…

开发问题记录

1、MySQL死锁问题解决 Waiting for table metadata lock &#xff1a; Alter table qimao.qimao_content_distribute drop index idx_content_id,add UNIQUE ind直接执行 kill id&#xff0c;杀掉死锁进程即可 2、Mybatis 自动生成 使用MyBatis Generator自动生成实体、…

参加 JSConf China 2019 是怎样的体验?VS Code 和 TypeScript 都很火

JSConf China 2019 于 10 月 19-20 日于上海尚浦中心举行。很高兴作为讲师参加这次的 JSConf。Day 1在 Day 1 给大家聊了聊 The Beauty of TypeScript。简单总结下我讲的 TypeScript 的 session。千言万语&#xff0c;汇聚成下面两页的 PPT。TypeScript 的使用场景&#xff08;…

记一次应用配置的数据库连接被打满问题

线上应用&#xff0c;配置的数据库连接数为50&#xff0c;正常情况是已经够用了&#xff0c;但是有天发现50个连接全部被占满&#xff0c;并且长时间无法恢复&#xff0c;重启服务后会好一段时间。 1、问题现象 Druid获取MySQL数据库连接超时&#xff0c;超时时间设置的为60s…

Caffe阅读代码并修改

这个教程是最好理解的了 http://city.shaform.com/blog/2016/02/26/caffe.html 主要分成四個部份來講。首先是整個 Caffe 的大架構&#xff0c;以及一些重要的元件。 其次&#xff0c;我也研究了如何自己新增一個 layer。 接下來&#xff0c;再重新回到 Caffe 做更深入的解析…

ABP v1.0正式发布

经过长时间的开发终于发布了ABP v1.0&#xff01;感谢为该项目做出了贡献的你~https://github.com/abpframework/abp/releases

JVM解惑:消失的异常堆栈,log中打印异常堆栈为空

最近线上发现很多异常没有堆栈信息&#xff0c;只有一句描述&#xff0c;如下&#xff1a; java.lang.NullPointerException: null排查问题时受到了一些阻碍。然后发现无论是在本地环境还是测试环境&#xff0c;堆栈信息都可以正常打印&#xff0c;使用的是同一份日志配置文件…