我们在进行webapi服务开发时,会遇到一些多个版本的api共存的情况发生,例如某一版本APP上线后,需求发生变更,需要在下一个升级版本更新API,但同时又需要保证这个APP版本能正常使用,这时候就需要采用API服务版本控制。

版本控制一般有以下几种方式:

  1. 在url上增加查询字符串参数的方式,追加版本,例如 api/service?v=2
  2. 在url路径上增加版本。例如:api/v2/service(这种方式个人认为目前是最优雅的方式)
  3. 在http请求head中加入版本标识

目前微软提供了 Microsoft.AspNetCore.Mvc.Versioning 组件,能够支持以上几种方式。

组件注册

            services.AddApiVersioning(options =>
{
options.ReportApiVersions = true;
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(, );
});
  • ReportAPIVersions: 这是可选的。但是, 当设置为 true 时, API 将返回响应标头中支持的版本信息。
  • AssumeDefaultVersionWhenUnspecified: 此选项将用于不提供版本的请求。默认情况下, 假定的 API 版本为1.0。(这个经测试对url追加版本方式不起作用)
  • DefaultApiVersion: 此选项用于指定在请求中未指定版本时要使用的默认 API 版本。这将默认版本为1.0。

几个重要的类

  • ApiVersion 特性标识当前Controller的版本,注意路由的配置。这里我们采用了第 2 个版本控制方式
  • MapToApiVersion 属性允许将单个 API 操作映射到某一版本

实现一个小需求:在同一个Controller里面新增一个api版本

  http://localhost:5000/gateway/api/user/headclaims           --->指向 默认v1版本

  http://localhost:5000/gateway/api/v1/user/headclaims      ---->指向 v1版本

  http://localhost:5000/gateway/api/v2/user/headclaims      ---->指向 v2版本

配置如下:

    [ApiVersion("1.0")]
    [ApiVersion("2.0")]
    //多路由支持
    [Route("api/v{version:apiVersion}/[controller]")]
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserAppService _userService;
        public UserController(IUserAppService userService)
        {
            _userService = userService;
        }
 
        [Route("headclaims")]
        [HttpGet]
        public IActionResult HeadClaims()
        {
            var claimTypes = new List<string> { "name", "phone", "userId", "introduce" };
            var claimHeads = Request.Headers.Where(x => claimTypes.Contains(x.Key));
            var user = Request.HttpContext.User;
            if (claimHeads == null) return Ok();
            var returnObj = new JObject();
            foreach (var ch in claimHeads)
            {
                returnObj.Add(ch.Key, ch.Value.ToString());
            }
            return Ok(returnObj);
        }
        [Route("headclaims")]
        [HttpGet, MapToApiVersion("2.0")]
        public IActionResult HeadClaimsv2()
        {
            var claimTypes = new List<string> { "name", "phone" };
            var claimHeads = Request.Headers.Where(x => claimTypes.Contains(x.Key));
            var user = Request.HttpContext.User;
            if (claimHeads == null) return Ok();
            var returnObj = new JObject();
            foreach (var ch in claimHeads)
            {
                returnObj.Add(ch.Key, ch.Value.ToString());
            }
            return Ok(returnObj);
        }
    }

API服务版本控制 Microsoft.AspNetCore.Mvc.Versioning的更多相关文章

  1. Orchard Core 版本冲突 The type 'FormTagHelper' exists in both 'Microsoft.AspNetCore.Mvc.TagHelpers, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' and...

    最近老大让我看Orchard Core,这是一个CMS系统.可以先参考大佬的文章:https://www.cnblogs.com/shanyou/archive/2018/09/25/9700422. ...

  2. TypeLoadException: Could not load type 'Microsoft.AspNetCore.Mvc.Internal.IHttpResponseStreamWriterFactory' from assembly 'Microsoft.AspNetCore.Mvc.Core, Version=2.1.2.0 ...

    今天调试 asp.net core 2.0 项目时遇到了如下错误: TypeLoadException: Could not load type 'Microsoft.AspNetCore.Mvc.I ...

  3. Core 3.1 MVC 抛异常“InvalidOperationException: No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory' has been registered.”

    .NET Core 的版本是 3.1遇到的问题是 Action 中 return View() 的时候报错 An unhandled exception occurred while processi ...

  4. .Net Core Api 使用版本控制

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

  5. 002.Create a web API with ASP.NET Core MVC and Visual Studio for Windows -- 【在windows上用vs与asp.net core mvc 创建一个 web api 程序】

    Create a web API with ASP.NET Core MVC and Visual Studio for Windows 在windows上用vs与asp.net core mvc 创 ...

  6. 从ASP.Net Core Web Api模板中移除MVC Razor依赖项

    前言 :本篇文章,我将会介绍如何在不包括MVC / Razor功能和包的情况下,添加最少的依赖项到ASP.NET Core Web API项目中. 一.MVC   VS WebApi (1)在ASP. ...

  7. 使用Microsoft.AspNetCore.TestHost进行完整的功能测试

    简介 Microsoft.AspNetCore.TestHost是可以用于Asp.net Core 的功能测试工具.很多时候我们一个接口写好了,单元测试什么的也都ok了,需要完整调试一下,检查下单元测 ...

  8. 错误记录——fail: Microsoft.AspNetCore.Server.Kestrel[13]

    fail: Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HLPN4417RVEM", Request id &q ...

  9. Web API 接口版本控制 SDammann.WebApi.Versioning

    前言 在设计对外 Web API 时,实务上可能会有新旧版本 API 并存的情况,例如开放 Web API 给厂商串接,但同一个服务更新版本时,不一定所有厂商可以在同一时间都跟着更新他们的系统,但如果 ...

随机推荐

  1. hibernate中lazy的使用

    lazy,延迟加载 Lazy的有效期:只有在session打开的时候才有效:session关闭后lazy就没效了. lazy策略可以用在: * <class>标签上:可以取值true/fa ...

  2. ADB命令-1

    1.adb -s 指定设备号(用于已连接多个设备时) 2.adb install -r -t xxx 安装程序 3.adb pull  设备目录   本地目录 复制文件命令 4.adb push 向设 ...

  3. [LC] 105. Construct Binary Tree from Preorder and Inorder Traversal

    Given preorder and inorder traversal of a tree, construct the binary tree. Note:You may assume that ...

  4. [LC] 520. Detect Capital

    Given a word, you need to judge whether the usage of capitals in it is right or not. We define the u ...

  5. 用C#实现一个百度万年历

    目录 背景 实现步骤 关键点 结束语 背景 命理学是对人生命运规律的探索,以人的各式各样的数字(出生年月日.姓名笔划等)来推测人的性格与命运并占卜推测未来会发生的事情.古今中外都有相关方面的理论,中国 ...

  6. plague|commence|gymnasium|triumph|jump

    N-COUNT 瘟疫:疫病A plague is a very infectious disease that spreads quickly and kills large numbers of p ...

  7. Welcome to Fan Ouyang’s website!

    Welcome to Fan Ouyang's website! 欧阳璠,哲学博士,湖南娄底人. 目前为浙江大学教育学院课程与学习科学系教育技术专业百人计划研究员. 2013-2018年 明尼苏达大学 ...

  8. IO流文件拷贝

    目录 IO流文件拷贝 前言 字节流(使用FileInputStream和FileOutputStream读取每一个字节...) 字节流(使用FileInputStream和FileOutputStre ...

  9. supervised learning|unsupervised learning

    监督学习即是supervised learning,原始数据中有每个数据有自己的数据结构同时有标签,用于classify,机器learn的是判定规则,通过已成熟的数据training model达到判 ...

  10. UML 类图介绍

    UML 类图介绍 一. UML 简介 UML ( Unified Modeling Language )即统一建模语言,是 OMG ( Object Management Group )发表的图标式软 ...