.Net Core Api 使用版本控制详解

Karli ·
更新时间:2024-09-21
· 698 次阅读

Api的版本控制是Api开发中经常遇到的问题, 在大部分中大型项目都需要使用到Api的版本控制

在本篇博客中,我们将说明一下如何在.Net Core Api项目中使用Api版本控制。

本篇博客中测试项目的开发环境:

Visual Studio 2017 .Net Core 2.1 SDK

1,安装Microsoft.AspNetCore.Mvc.Versioning

NET Core Mvc中,微软官方提供了一个可用的Api版本控制库Microsoft.AspNetCore.Mvc.Versioning。

2,修改Startup类

这里我们需要在Startup类的ConfigureService方法中添加以下代码。

// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddApiVersioning(o => { o.ReportApiVersions = true; o.AssumeDefaultVersionWhenUnspecified = true; o.DefaultApiVersion = new ApiVersion(1, 0); //o.ApiVersionReader = new HeaderApiVersionReader("x-api-version"); }); }

3,代码

//版本1控制器 [ApiVersion("1.0", Deprecated = true)] [Route("api/values")] [ApiController] public class ValuesV1Controller : ControllerBase { [HttpGet] public IEnumerable<string> Get() { return new string[] { "这是版本1.0返回的——数据1", "这是版本1.0返回的——数据2" }; } } //版本2控制器 [ApiVersion("2.0")] [Route("api/values")] [ApiController] public class ValuesV2Controller : ControllerBase { [HttpGet] public IEnumerable<string> Get() { return new string[] { "这是版本2.0返回的——数据1", "这是版本2.0返回的——数据2" }; } }

4,访问

https://localhost:44319/api/values

https://localhost:44319/api/values?api-version=1.0

https://localhost:44319/api/values?api-version=2.0

您可能感兴趣的文章:asp.net core集成JWT的步骤记录.net core webapi jwt 更为清爽的认证详解Asp.Net Core基于JWT认证的数据接口网关实例代码深入讲解.Net Core中的Api版本控制.net core在服务器端获取api传递的参数过程.NET core 3.0如何使用Jwt保护api详解



core net .NET 版本 版本控制 api

需要 登录 后方可回复, 如果你还没有账号请 注册新账号