前言:

 在日常项目开发中,随着项目需求不断的累加、不断的迭代;项目服务接口需要向下兼容历史版本;前些时候就因为Api接口为做版本管理导致接口对低版本兼容处理不友好。

 最近就像了解下如何实现WebApi版本控制,那么版本控制有什么好处呢?

 WebApi版本控制的好处

  • 有助于及时推出功能, 而不会破坏现有系统,兼容性处理更友好。
  • 它还可以帮助为选定的客户提供额外的功能。

 接下来就来实现版本控制以及在Swagger UI中接入WebApi版本

一、WebApi版本控制实现

  通过Microsoft.AspNetCore.Mvc.Versioning 实现webapi 版本控制

  • 创建WebApi项目,添加Nuget包:Microsoft.AspNetCore.Mvc.Versioning
Install-Package Microsoft.AspNetCore.Mvc.Versioning 
  • 修改项目Startup文件,使用Microsoft.AspNetCore.Mvc.Versioning
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//根据需要设置,以下内容
services.AddApiVersioning(apiOtions =>
{
//返回响应标头中支持的版本信息
apiOtions.ReportApiVersions = true;
//此选项将用于不提供版本的请求。默认情况下, 假定的 API 版本为1.0
apiOtions.AssumeDefaultVersionWhenUnspecified = true;
//缺省api版本号,支持时间或数字版本号
apiOtions.DefaultApiVersion = new ApiVersion(1, 0);
//支持MediaType、Header、QueryString 设置版本号;缺省为QueryString、UrlSegment设置版本号;后面会详细说明对于作用
apiOtions.ApiVersionReader = ApiVersionReader.Combine(
new MediaTypeApiVersionReader("api-version"),
new HeaderApiVersionReader("api-version"),
new QueryStringApiVersionReader("api-version"),
new UrlSegmentApiVersionReader());
});
services.AddControllers();
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection(); //使用ApiVersioning
app.UseApiVersioning();

app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
  • WebApi设置版本:

  a)通过ApiVersion标记指定指定控制器或方法的版本号;Url参数控制版本(QueryStringApiVersionReader),如下:

namespace WebAPIVersionDemo.Controllers
{
[ApiController]
[Route("[controller]")]
//Deprecated=true:表示v1即将弃用,响应头中返回
[ApiVersion("1.0", Deprecated = true)]
[ApiVersion("2.0")]public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]{"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"}; [HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = $"v1:{Summaries[rng.Next(Summaries.Length)]}"
})
.ToArray();
}
}
}

  通过参数api-version参数指定版本号;调用结果:

  

  b)通过Url Path Segment控制版本号(UrlSegmentApiVersionReader):为控制器添加路由方式如下,apiVersion为固定格式  

[Route("/api/v{version:apiVersion}/[controller]")]

  调用方式:通过调用路径传入版本号,如:http://localhost:5000/api/v1/weatherforecast

   

  c)通过Header头控制版本号:在Startup中设置(HeaderApiVersionReader、MediaTypeApiVersionReader

apiOtions.ApiVersionReader = ApiVersionReader.Combine(
new MediaTypeApiVersionReader("api-version"),
new HeaderApiVersionReader("api-version"));

  调用方式,在请求头或中MediaType中传递api版本,如下:

   

   

  • 其他说明:

    a)ReportApiVersions设置为true时, 返回当前支持版本号(api-supported-versions);Deprecated 参数设置为true表示已弃用,在响应头中也有显示(api-deprecated-versions):

    

    b)MapToApiVersion标记:允许将单个 API 操作映射到任何版本(可以在v1的控制器中添加v3的方法);在上面控制器中添加以下代码,访问v3版本方法

[HttpGet]
[MapToApiVersion("3.0")]
public IEnumerable<WeatherForecast> GetV3()
{
//获取版本
string v = HttpContext.GetRequestedApiVersion().ToString();
var rng = new Random();
return Enumerable.Range(1, 1).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = $"v{v}:{Summaries[rng.Next(Summaries.Length)]}"
})
.ToArray();
}

    

   c)注意事项:

    1、路径中参数版本高于,其他方式设置版本

    2、多种方式传递版本,只能采用一种方式传递版本号

    3、SwaggerUI中MapToApiVersion设置版本不会单独显示    

二、Swagger UI中版本接入

 1、添加包:Swashbuckle.AspNetCore、Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer   

//swaggerui 包
Install-Package Swashbuckle.AspNetCore
//api版本
Install-Package Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer

 2、修改Startup代码:

public class Startup
{
/// <summary>
/// Api版本提者信息
/// </summary>
private IApiVersionDescriptionProvider provider; // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(); //根据需要设置,以下内容
services.AddApiVersioning(apiOtions =>
{
//返回响应标头中支持的版本信息
apiOtions.ReportApiVersions = true;
//此选项将用于不提供版本的请求。默认情况下, 假定的 API 版本为1.0
apiOtions.AssumeDefaultVersionWhenUnspecified = true;
//缺省api版本号,支持时间或数字版本号
apiOtions.DefaultApiVersion = new ApiVersion(1, 0);
//支持MediaType、Header、QueryString 设置版本号;缺省为QueryString设置版本号
apiOtions.ApiVersionReader = ApiVersionReader.Combine(
new MediaTypeApiVersionReader("api-version"),
new HeaderApiVersionReader("api-version"),
new QueryStringApiVersionReader("api-version"),
new UrlSegmentApiVersionReader());
}); services.AddVersionedApiExplorer(option =>
{
option.GroupNameFormat = "接口:'v'VVV";
option.AssumeDefaultVersionWhenUnspecified = true;
});
this.provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>();
services.AddSwaggerGen(options =>
{
foreach (var description in provider.ApiVersionDescriptions)
{
options.SwaggerDoc(description.GroupName,
new Microsoft.OpenApi.Models.OpenApiInfo()
{
Title = $"接口 v{description.ApiVersion}",
Version = description.ApiVersion.ToString(),
Description = "切换版本请点右上角版本切换"
}
);
}
options.IncludeXmlComments(this.GetType().Assembly.Location.Replace(".dll", ".xml"), true
);
});
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//…… //使用ApiVersioning
app.UseApiVersioning(); //启用swaggerui,绑定api版本信息
app.UseSwagger();
app.UseSwaggerUI(c =>
{
foreach (var description in provider.ApiVersionDescriptions)
{
c.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
}
});
//……
}
}

 3、运行效果:  

  

其他: 

 示例地址:https://github.com/cwsheng/WebAPIVersionDemo

ASP.NET Core WebApi版本控制的更多相关文章

  1. Asp.Net.Core WebApi 版本控制

    前言 在后端Api的开发过程中,无法避免的会遇到接口迭代的过程,如何保证新老接口的共存和接口的向前的兼容呢,这时候就需要对Api进行版本的控制,那如何优雅的控制Api的版本呢? 开始 Microsof ...

  2. ASP.Net Core WebApi几种版本控制对比

    版本控制的好处: (1)助于及时推出功能, 而不会破坏现有系统. (2)它还可以帮助为选定的客户提供额外的功能. API 版本控制可以采用不同的方式进行控制,方法如下: (1)在 URL 中追加版本或 ...

  3. 零基础ASP.NET Core WebAPI团队协作开发

    零基础ASP.NET Core WebAPI团队协作开发 相信大家对“前后端分离”和“微服务”这两个词应该是耳熟能详了.网上也有很多介绍这方面的文章,写的都很好.我这里提这个是因为接下来我要分享的内容 ...

  4. ASP.NET Core WebApi构建API接口服务实战演练

    一.ASP.NET Core WebApi课程介绍 人生苦短,我用.NET Core!提到Api接口,一般会想到以前用到的WebService和WCF服务,这三个技术都是用来创建服务接口,只不过Web ...

  5. asp.net core webapi之跨域(Cors)访问

    这里说的跨域是指通过js在不同的域之间进行数据传输或通信,比如用ajax向一个不同的域请求数据,或者通过js获取页面中不同域的框架中(iframe)的数据.只要协议.域名.端口有任何一个不同,都被当作 ...

  6. ASP.NET Core WebAPI 开发-新建WebAPI项目

    ASP.NET Core WebAPI 开发-新建WebAPI项目, ASP.NET Core 1.0 RC2 即将发布,我们现在来学习一下 ASP.NET Core WebAPI开发. 网上已经有泄 ...

  7. Asp.net Core WebApi 使用Swagger做帮助文档,并且自定义Swagger的UI

    WebApi写好之后,在线帮助文档以及能够在线调试的工具是专业化的表现,而Swagger毫无疑问是做Docs的最佳工具,自动生成每个Controller的接口说明,自动将参数解析成json,并且能够在 ...

  8. Asp.Net Core WebApi学习笔记(四)-- Middleware

    Asp.Net Core WebApi学习笔记(四)-- Middleware 本文记录了Asp.Net管道模型和Asp.Net Core的Middleware模型的对比,并在上一篇的基础上增加Mid ...

  9. Asp.net core WebApi 使用Swagger生成帮助页

    最近我们团队一直进行.net core的转型,web开发向着前后端分离的技术架构演进,我们后台主要是采用了asp.net core webapi来进行开发,开始每次调试以及与前端人员的沟通上都存在这效 ...

随机推荐

  1. 利用selenium抓取网页的ajax请求

    部门需要一个自动化脚本,完成web端界面功能的冒烟,并且需要抓取加载页面时的ajax请求,从接口层面判断请求是否成功.查阅了很多资料都没有人有过相关问题的处理经验,在处理过程中也踩了很多坑,所以如果你 ...

  2. DEDECMS的20位MD5加密密文解密

    解密20位md5,20位md5加密算法.   dedecms的20位md5加密算噶是从32位md5中截取的20位,所以去掉前3位喝最后1位,即可获得16位md5值,即可破解15位md5.   例如:  ...

  3. Jcrop图片裁剪

    一.引入js和css 二.实现 1.jsp页面 <%-- Created by IntelliJ IDEA. User: a Date: 2019/8/19 Time: 9:36 To chan ...

  4. 2019牛客暑期多校训练营(第五场)C - generator 2 (BSGS)

    题目链接 题意: 给定\(n,x_0,a,b,p\),有递推式\(x_i = (a \cdot x_{i-1} +b)\%p\). 有\(Q\)个询问,每次询问给定一个\(v\),问是否存在一个最小的 ...

  5. AtCoder Beginner Contest 188 E - Peddler (树)

    题意:有\(n\)个点,\(m\)条单向边,保证每条边的起点小于终点,每个点都有权值,找到联通的点的两个点的最大差值. 题解:因为题目说了起点小于终点,所以我们可以反向存边,然后维护连通边的前缀最小值 ...

  6. Codeforces Round #550 (Div. 3) E. Median String (思维,模拟)

    题意:给你两个字符串\(s\)和\(t\),保证\(t\)的字典序大于\(s\),求他们字典序中间的字符串. 题解:我们假设题目给的不是字符串,而是两个10禁止的正整数,那么输出他们之间的数只要把他两 ...

  7. 微服务架构学习Day01-SpringBoot入门

    基本概念 SpringBoot的优点: 可以创建独立的Spring应用 SpringBoot嵌入Tomcat,Jetty和Unsertow, 不需要部署war文件 根据需要通过maven获取start ...

  8. Kibana 地标图可视化

    ElasticSearch 可以使用 ingest-geoip 插件可以在 Kibana 上对 IP 进行地理位置分析, 这个插件需要 Maxmind 的 GeoLite2 City,GeoLite2 ...

  9. docker的底层-隔离的核心

    在了解底层原理之前: 说几个名词: 解耦状态: 所有东西都没有重复,任何东西都没有公用的地方. 半解耦状态:有部分共同的一起用,其他的独立 完全解耦状态: 就是各自都是独立没有重复. kvm:完全解耦 ...

  10. (20002, b'DB-Lib error message 20002, severity 9:\nAdaptive Server connection failed (127.0.0.1:3306)\n')

    使用python 3.7 pymssql 连接本地mysql 5.6 报错 解决:参考 https://www.cnblogs.com/springbrotherhpu/p/11503139.html ...