.NetCore使用Swagger进行单版本或多版本控制处理
前面已经介绍过了Swagger的基础使用了
下面继续分别详细说明下 不添加版本控制以及添加版本控制的使用情况,其实也基本一致,对看起来可能更加容易理解
第一步 导入nuget包
nuget导入Swashbuckle.AspNetCore (对应有Swashbuckle.AspNetCore.Swagger、Swashbuckle.AspNetCore.SwaggerGen、Swashbuckle.AspNetCore.SwaggerUI)
版本控制还需要引入
Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer
Microsoft.AspNetCore.Mvc.Versioning
第二步 添加服务及配置
下面代码中都结合了IdentityServer4中的相关设置,可以忽略
非版本控制
ConfigServices中添加如下代码
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
{
Version = "v1.0",
Title = "体检微服务接口"
}); var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var xmlPath = Path.Combine(basePath, "ExaminationServicesApi.xml");
options.IncludeXmlComments(xmlPath); var xmlmodelPath =
Path.Combine(basePath, "ExaminationServicesDomain.xml");
options.IncludeXmlComments(xmlmodelPath); #region Swagger添加授权验证服务 //options.AddSecurityDefinition("Bearer", new ApiKeyScheme
//{
// Description = "JWT Bearer 授权 \"Authorization: Bearer+空格+token\"",
// Name = "Authorization",
// In = "header",
// Type = "apiKey"
//}); options.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Type = "oauth2",
Flow = "implicit",
AuthorizationUrl = _authorityconfig.Authority + "/connect/authorize",
Scopes = new Dictionary<string, string>
{
//{ "openid", "身份信息" } ,
//{ "profile", "个人基本信息" } ,
{ "userservicesapi", "用户服务" },
{ "examinationservicesapi", "体检服务" }
}
});
options.OperationFilter<CustomOperationFilter>();
#endregion });
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApi");
c.OAuthClientId("testuserservicesapiexaminationservicesapi");
c.OAuthAppName("体检服务");
});
这里要注意到我添加了2个xml 一个是apicontroller的获取注释描述,如果需要model相关的描述可以将model所在的应用程序集xml处理下,以便于在接口文档上可以看到model的先关说明
版本控制
ConfigServices中添加如下代码 只不过是动态的处理了版本信息
services.AddApiVersioning(option =>
{
option.AssumeDefaultVersionWhenUnspecified = true;
option.ReportApiVersions = false;
})
.AddMvcCore().AddVersionedApiExplorer(option => {
option.GroupNameFormat = "'v'VVV";
option.AssumeDefaultVersionWhenUnspecified = true;
});
services.AddSwaggerGen(options =>
{
var provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>();
foreach (var description in provider.ApiVersionDescriptions)
{
options.SwaggerDoc(description.GroupName,
new Info()
{
Title = $"体检微服务接口 v{description.ApiVersion}",
Version = description.ApiVersion.ToString(),
Description = "切换版本请点右上角版本切换",
Contact = new Contact() { Name = "黎又铭", Email = "2939828886@qq.com" }
}
);
} //options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
//{
// Version = "v1.0",
// Title = "体检微服务接口"
//}); var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var xmlPath = Path.Combine(basePath, "ExaminationServicesApi.xml");
options.IncludeXmlComments(xmlPath); var xmlmodelPath =
Path.Combine(basePath, "ExaminationServicesDomain.xml");
options.IncludeXmlComments(xmlmodelPath); #region Swagger添加授权验证服务 //options.AddSecurityDefinition("Bearer", new ApiKeyScheme
//{
// Description = "JWT Bearer 授权 \"Authorization: Bearer+空格+token\"",
// Name = "Authorization",
// In = "header",
// Type = "apiKey"
//}); options.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Type = "oauth2",
Flow = "implicit",
AuthorizationUrl = _authorityconfig.Authority + "/connect/authorize",
Scopes = new Dictionary<string, string>
{
//{ "openid", "身份信息" } ,
//{ "profile", "个人基本信息" } ,
{ "userservicesapi", "用户服务" },
{ "examinationservicesapi", "体检服务" } }
});
options.OperationFilter<CustomOperationFilter>();
#endregion });
app.UseSwagger();
app.UseSwaggerUI(c =>
{ foreach (var description in provider.ApiVersionDescriptions)
{
c.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
}
//c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApi");
c.OAuthClientId("testuserservicesapiexaminationservicesapi");
c.OAuthAppName("体检服务");
});
对比两种情况可以看出实际上就多出来一个办理版本信息而已,ApiVersionDescriptions 其实就是通过这个特性动态遍历了版本信息,所以多版本控制只需要在ApiController中添加好相关的属性标签即可
第三步 使用
[ApiVersion("1.0")]
[Route("api/v{api-version:apiVersion}/[controller]")]
public class DemoController : ControllerBase
{
}
在前面代码中我们用到了 CustomOperationFilter这个处理,在这个操作过滤器中我在之前的代码中添加授权及文件上传,这里我们使用版本控制还需要在里面添加好版本参数描述处理
public class CustomOperationFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{ #region Swagger版本描述处理
foreach (var parameter in operation.Parameters.OfType<NonBodyParameter>())
{
var description = context.ApiDescription.ParameterDescriptions.First(p => p.Name == parameter.Name); if (parameter.Description == null)
{
parameter.Description = description.ModelMetadata.Description;
}
} #endregion #region Swagger授权过期器处理
if (operation.Security == null)
operation.Security = new List<IDictionary<string, IEnumerable<string>>>();
var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
{ {"oauth2", new List<string> { "openid", "profile", "examinationservicesapi" }}
};
operation.Security.Add(oAuthRequirements);
#endregion #region Swagger 文件上传处理 var files = context.ApiDescription.ActionDescriptor.Parameters.Where(n => n.ParameterType == typeof(IFormFile)).ToList();
if (files.Count > )
{
for (int i = ; i < files.Count; i++)
{
if (i == )
{
operation.Parameters.Clear();
}
operation.Parameters.Add(new NonBodyParameter
{
Name = files[i].Name,
In = "formData",
Description = "Upload File",
Required = true,
Type = "file"
}); }
operation.Consumes.Add("multipart/form-data");
} #endregion
}
}
运行程序看效果


版本控制就搞定了,这里需要说明的是看下面的图
额外说明

版本是不是必须的、以及描述就是在CustomOperationFilter中处理下默认的说明,你可以这样写
if (parameter.Description == null)
{
parameter.Description ="填写版本号如:1.0";
} parameter.Required=false; //设置非必填或非必填
下面看下效果,已经有注释了和设置了的非必填项目

这里额外在说一点的就是
[ApiVersion("1.0", Deprecated = false)]
Deprecated 这个属性设置 True :标识是否弃用API ,在设置为true的情况下来看下效果

1.0版本已经是弃用了,这里又要额外说下与这个关联的属性了就是在服务配置选项中的 ReportApiVersions 设置 用下面的配置
services.AddApiVersioning(option =>
{
option.ReportApiVersions = false;
})
.AddMvcCore().AddVersionedApiExplorer(option => {
option.GroupNameFormat = "'v'VVV";
option.AssumeDefaultVersionWhenUnspecified = true;
option.DefaultApiVersion = new ApiVersion(, );
});
false:不再请求响应中添加 版本报告信息,下图中已经不会显示我一用的版本信息了

上面默认版本 DefaultApiVersion 我设置了1.0 在代码中出现2个版本路由地址一样,在没有填写版本号的情况下使用默认版本
AssumeDefaultVersionWhenUnspecified:true 是否在没有填写版本号的情况下使用默认版本
.NetCore使用Swagger进行单版本或多版本控制处理的更多相关文章
- .NetCore WebApi —— Swagger版本控制
目录: .NetCore WebApi——Swagger简单配置 .NetCore WebApi——基于JWT的简单身份认证与授权(Swagger) .NetCore WebApi —— Swagge ...
- .NetCore WebApi——Swagger简单配置
在前后端分离的大环境下,API接口文档成为了前后端交流的一个重点.Swagger让开发人员摆脱了写接口文档的痛苦. 官方网址:https://swagger.io/ 在.Net Core WebApi ...
- 为.netcore助力--WebApiClient正式发布core版本
1 前言 WebApiClient已成熟稳定,发布了WebApiClient.JIT和WebApiClient.AOT两个nuget包,累计近10w次下载.我对它的高可扩展性设计相当满意和自豪,但We ...
- Centos 7上安装Python3.x(单版本)
Centos7默认安装的是2.7,这里选择安装使用Python3.6.3 安装Python3.6.3 1.安装python3 需要的依赖包 yum install -y openssl-devel b ...
- netcore 添加swagger
1.添加相应的nuget包 2.配置服务和swaggerui startup.cs 中 configureServices 中添加下面代码: //swagger services.AddSwagge ...
- 跟我一起学.NetCore之Swagger让前后端不再烦恼及界面自定义
前言 随着前后端分离开发模式的流行,接口对接.联调成为常事,前端同事会经常问:我需要调哪个接口?这个接口数据格式是啥?条件都传啥? 对于一些紧急接口可能会采取沟通对接,然后补文档,其他的都会回一句:看 ...
- .NetCore利用Swagger生成 XML文档需要注意生成路径的地址
发布的时候如果用 release dotnet publish --configuration release dotnet publish 默认都是debug 会出现 XML丢失问题,其实可以看下工 ...
- 利用swagger和API Version实现api版本控制
场景: 在利用.net core进行api接口开发时,经常会因为需求,要开发实现统一功能的多版本的接口.比如版本V1是给之前用户使用,然后新用户有新需求,这时候可以单独给这个用户写接口,也可以在V1基 ...
- NetCore 3.0 中使用Swagger生成Api说明文档及升级报错原因
认识Swagger Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.总体目标是使客户端和文件系统作为服务器以同样的速度来更新.文件的方法,参 ...
随机推荐
- 【bzoj4596】[Shoi2016]黑暗前的幻想乡 容斥原理+矩阵树定理
题目描述 给出 $n$ 个点和 $n-1$ 种颜色,每种颜色有若干条边.求这张图多少棵每种颜色的边都出现过的生成树,答案对 $10^9+7$ 取模. 输入 第一行包含一个正整数 N(N<=17) ...
- BZOJ3881 Coci2015Divljak(AC自动机+树上差分+树状数组)
建出AC自动机及其fail树,每次给新加入的串在AC自动机上经过的点染色,问题即转化为子树颜色数.显然可以用dfs序转成序列问题树状数组套权值线段树解决,显然过不掉.事实上直接树上差分,按dfs序排序 ...
- idea和eclipse的区别
使用基于IntelliJ的IDE,都会对project和module的关系比较糊涂.用简单的一句话来概括是: IntelliJ系中的Project相当于Eclipse系中的workspace.Inte ...
- BZOJ 2668 [cqoi2012]交换棋子 | 最小费用最大流
传送门 BZOJ 2668 题解 同时分别限制流入和流出次数,所以把一个点拆成三个:入点in(x).中间点mi(x).出点ou(x). 如果一个格子x在初始状态是黑点,则连(S, mi(x), 1, ...
- 洛谷 P4112 [HEOI2015]最短不公共子串 解题报告
P4112 [HEOI2015]最短不公共子串 题目描述 在虐各种最长公共子串.子序列的题虐的不耐烦了之后,你决定反其道而行之. 一个串的"子串"指的是它的连续的一段,例如bcd是 ...
- Qtree4——动态点分治
题目描述 给出一棵边带权的节点数量为n的树,初始树上所有节点都是白色.有两种操作: C x,改变节点x的颜色,即白变黑,黑变白 A,询问树中最远的两个白色节点的距离,这两个白色节点可以重合(此时距离为 ...
- token的理解
今天学习了token,它的英文意思是令牌的意思.在我理解即像通行证一样,在用户登录成功系统后,会为这个用户颁发一个token,这样它去其他系统都免登录,因为有了这个令牌. token的生成我们可以用U ...
- string::replace
#include <string> #include <cctype> #include <algorithm> #include <iostream> ...
- 解决小米note5 安装了google play store 打不开的问题
打不开的原因是缺少了google play store 运行的一些后台程序 去豌豆荚下载如下谷歌安装器(注:安装器有很多种,我试了如下这种成功) 重启手机,google play store 即可正常 ...
- Scala进阶之路-高级数据类型之集合的使用
Scala进阶之路-高级数据类型之集合的使用 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. Scala 的集合有三大类:序列 Seq.集 Set.映射 Map,所有的集合都扩展自 ...