webapi_swagger版本管理
什么要做api版本管理
前后端分离的系统,一个后端(这里用webapi)往往供多个前端调用,pc端、移动端或者一些给某些客户定制的前端版本。
随着时间的推移,总会有新功能的添加和老功能的升级,但是有些前端版本并不需要新增加或升级的功能,它也不想因为后端升级了而被迫跟着升级,这时就需要后端在升级时把原接口的版本保留下来并保证其功能和原来一致。于是后端就出现了不同版本的API接口。
webapi+swagger版本管理实现
代码GitHub地址:SomeExperiments
- 安装nuget包
Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer
Swashbuckle.AspNetCore - 修改Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddApiVersioning(o =>
{
//为true时,API会在响应的header中返回支持的版本信息
o.ReportApiVersions = true;
请求中未指定版本时默认为1.0
//o.DefaultApiVersion = new ApiVersion(1, 0);
版本号以什么形式,什么字段传递
//o.ApiVersionReader = ApiVersionReader.Combine(new HeaderApiVersionReader("api-version"));
在不提供版本号时,默认为1.0 如果不添加此配置,不提供版本号时会报错"message": "An API version is required, but was not specified."
//o.AssumeDefaultVersionWhenUnspecified = true;
默认以当前最高版本进行访问
//o.ApiVersionSelector = new CurrentImplementationApiVersionSelector(o);
})