如何在.Net Core Api中使用版本控制

发布时间:2021-06-07 17:49:26 作者:Leah
来源:亿速云 阅读:158

如何在.Net Core Api中使用版本控制?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

1,安装Microsoft.AspNetCore.Mvc.Versioning

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

如何在.Net Core Api中使用版本控制

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" };
    }
  }

关于如何在.Net Core Api中使用版本控制问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. ASP.Net Core中WebApi几种版本控制对比的示例分析
  2. 如何配置swagge和控制net core webapi

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

上一篇:怎么在.NET Core中使用MemoryCache 实现缓存域

下一篇:怎么在asp.net core项目中使用MongoDB

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》