您现在的位置是:网站首页> 编程资料编程资料
.Net Core Api 使用版本控制详解_实用技巧_
2023-05-24
333人已围观
简介 .Net Core Api 使用版本控制详解_实用技巧_
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 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 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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
您可能感兴趣的文章:
相关内容
- 详解.NET Core中的数据保护组件_实用技巧_
- Visual Studio实现xml文件使用app.config、web.config等的智能提示_实用技巧_
- ASP.NET ashx实现无刷新页面生成验证码_实用技巧_
- 基于.net4.0实现IdentityServer4客户端JWT解密_实用技巧_
- asp.net core webapi项目配置全局路由的方法示例_实用技巧_
- Visual Studio 2017安装使用教程_实用技巧_
- Visual Studio 2017 IDE安装使用图文教程_实用技巧_
- Visual Studio IDE编写程序时不显示窗口或窗口一闪而逝的解决方法_实用技巧_
- vs2017软链接失效而导致无法进入安装界面的解决方法_实用技巧_
- Visual Studio 2017 community安装配置方法图文教程_实用技巧_
