zoukankan      html  css  js  c++  java
  • .Net Core Api 使用版本控制

    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

  • 相关阅读:
    根据表生成接收(zml)
    删除指定日期,指定设备的排产记录(zml)
    1029 Median
    1027 Colors in Mars (20 分)进制转换
    1028 List Sorting 排序
    1025 PAT Ranking
    1024 Palindromic Number(大数加法)
    1023 Have Fun with Numbers
    1022 Digital Library
    逆序打印乘法表
  • 原文地址:https://www.cnblogs.com/Akgu/p/9751879.html
Copyright © 2011-2022 走看看