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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。