<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          一文看懂:ASP.NET之Api版本控制!

          共 14025字,需瀏覽 29分鐘

           ·

          2021-05-20 21:35

          1. 優(yōu)點(diǎn)

          1. 有助于保護(hù)原有系統(tǒng),不受影響,并及時(shí)修改問題
          2. 可以實(shí)現(xiàn)用戶的私人定制(比如是付費(fèi)接口)
          3. 快速迭代

          2. API版本控制

          • 在URL中追加版本或者作為查詢字符串參數(shù)
          • 通過自動(dòng)以標(biāo)頭和通過接受標(biāo)頭

          2.1 安裝組件

          ASP.NET API versioning為您提供了一種功能強(qiáng)大但易于使用的方法,用于將API版本控制語義添加到使用ASP.NET構(gòu)建的新的和現(xiàn)有的REST服務(wù)中。API版本控制擴(kuò)展定義了簡(jiǎn)單的元數(shù)據(jù)屬性和約定,用于描述您的服務(wù)實(shí)現(xiàn)了哪些API版本。

              <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="4.2.0" />
              <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="4.2.0" />

          2.1.1 常用配置

          [ApiVersion("1.1")] //設(shè)置版本號(hào)
          [ApiVersionNeutral]//退出版本控制
          [MapToApiVersion("1.1")] //設(shè)置獨(dú)立版本
          [ApiVersion("1.0", Deprecated = true)]//api版本已經(jīng)被棄用
          HttpContext.GetRequestedApiVersion().ToString(); //訪問版本信息 

          2.2 QueryString來實(shí)現(xiàn)版本控制

          2.2.1 ConfigureServices中配置

                      //Versioning用來實(shí)現(xiàn)API的版本控制
                      services.AddApiVersioning(options =>
                      {
                          options.DefaultApiVersion = new ApiVersion(1, 1);//默認(rèn)版本號(hào)
                          options.AssumeDefaultVersionWhenUnspecified = true;//此選項(xiàng)將用于不提供版本的請(qǐng)求,默認(rèn)情況下假定API的版本為1.0
                          options.ReportApiVersions = true;//當(dāng)設(shè)置為true時(shí)候,api將返回響應(yīng)標(biāo)頭中支持的版本信息
                          //下面這句默認(rèn)不寫也可以
                          //options.ApiVersionReader = new QueryStringApiVersionReader(parameterNames: "api-version");//該名稱用于查詢時(shí)候使用
                      });

          2.2.2 控制器設(shè)置版本

          namespace NetCore_SwaggerVersion.Controllers.v1
          {
              /// <summary>
              /// 版本1.1
              /// </summary>
              [Route("api/[controller]")]
              [ApiController]
              [ApiVersion("1.1")]//可以設(shè)置多個(gè)
              [ApiVersion("1.2")]
              public class TestController : ControllerBase
              
          namespace NetCore_SwaggerVersion.Controllers.v2
          {
              /// <summary>
              /// 版本2.0
              /// </summary>
              [Route("api/[controller]")]
              [ApiController]
              [ApiVersion("2.6")]
              public class TestController : ControllerBase

          不同命名空間下可以存在相同的控制器

          2.2.3 特定方法設(shè)置版本

          [MapToApiVersion("1.1")]
          [HttpGet]
          public IEnumerable<string> Get()

          2.2.4 設(shè)置不受版本控制

              [ApiVersionNeutral]//退出版本控制
              [ApiController]
              [Route("api/[controller]/[action]")]
              public class WeatherForecastController : ControllerBase

          2.3.5 訪問地址

          http://localhost:5000/api/WeatherForecast/Get //不寫版本號(hào)的話走的是默認(rèn)的版本號(hào)
          http://localhost:5000/api/Test?api-version=1.1
          http://localhost:5000/api/Test?api-version=1.2
          http://localhost:5000/api/Test?api-version=2.6

          2.3 URL Path Segment來實(shí)現(xiàn)版本控制

          2.3.1 ConfigureServices中配置

                      //Versioning用來實(shí)現(xiàn)API的版本控制
                      services.AddApiVersioning(options =>
                      {
                          options.DefaultApiVersion = new ApiVersion(1, 1);//默認(rèn)版本號(hào)
                          options.AssumeDefaultVersionWhenUnspecified = true;//此選項(xiàng)將用于不提供版本的請(qǐng)求,默認(rèn)情況下假定API的版本為1.0
                          options.ReportApiVersions = true;//當(dāng)設(shè)置為true時(shí)候,api將返回響應(yīng)標(biāo)頭中支持的版本信息
                      });

          2.3.2 控制器設(shè)置版本

          namespace NetCore_SwaggerVersion.Controllers.v1
          {
              /// <summary>
              /// 版本1.1
              /// </summary>
              [Route("api/v{version:apiVersion}/[controller]")]
              [ApiController]
              [ApiVersion("1.0")]
              [ApiVersion("1.1")]//定義控制器提供哪個(gè)版本的API
              public class TestController : ControllerBase
              
          namespace NetCore_SwaggerVersion.Controllers.v2
          {
              /// <summary>
              /// 版本2.0
              /// </summary>
              [Route("api/v{version:apiVersion}/[controller]")]
              [ApiController]
              [ApiVersion("2.6")]
              public class TestController : ControllerBase

          不同命名空間下可以存在相同的控制器

          2.3.3 特定方法設(shè)置版本

          [MapToApiVersion("1.1")]
          [HttpGet]
          public IEnumerable<string> Get()

          2.3.4 設(shè)置不受版本控制

              [ApiVersionNeutral]//退出版本控制
              [ApiController]
              [Route("api/[controller]/[action]")]
              public class WeatherForecastController : ControllerBase

          2.3.5 訪問地址

          http://localhost:5000/api/v1.0/Test
          http://localhost:5000/api/v1.1/Test
          http://localhost:5000/api/v2.6/Test
          http://localhost:5000/api/WeatherForecast/Get 不受版本控制

          2.4 HTTP Headers來實(shí)現(xiàn)版本控制

          2.4.1 ConfigureServices中配置

                      //Versioning用來實(shí)現(xiàn)API的版本控制
                      services.AddApiVersioning(options =>
                      {
                          options.DefaultApiVersion = new ApiVersion(1, 1);//默認(rèn)版本號(hào)
                          options.AssumeDefaultVersionWhenUnspecified = true;//此選項(xiàng)將用于不提供版本的請(qǐng)求,默認(rèn)情況下假定API的版本為1.0
                          options.ReportApiVersions = true;//當(dāng)設(shè)置為true時(shí)候,api將返回響應(yīng)標(biāo)頭中支持的版本信息
                          //header傳遞版本信息
                          options.ApiVersionReader = new HeaderApiVersionReader("version");
                          options.ApiVersionSelector = new CurrentImplementationApiVersionSelector(options);//如果沒有傳輸版本號(hào),那么會(huì)使用最大版本號(hào)  LowestImplementedApiVersionSelector是最小版本號(hào)
                          options.UseApiBehavior = false;//是否使用API行為
                      });

          2.4.2 控制器設(shè)置版本

          namespace NetCore_SwaggerVersion.Controllers.v1
          {
              /// <summary>
              /// 版本1.1
              /// </summary>
              [Route("api/[controller]")]
              [ApiController]
              [ApiVersion("1.1")]//定義控制器提供哪個(gè)版本的API
              public class TestController : ControllerBase
              
          namespace NetCore_SwaggerVersion.Controllers.v2
          {
              /// <summary>
              /// 版本2.0
              /// </summary>
              [Route("api/[controller]")]
              [ApiController]
              [ApiVersion("2.6")]
              public class TestController : ControllerBase

          不同命名空間下可以存在相同的控制器

          2.4.3 特定方法設(shè)置版本

          [MapToApiVersion("1.1")]
          [HttpGet]
          public IEnumerable<string> Get()

          2.4.4 設(shè)置不受版本控制

              [ApiVersionNeutral]//退出版本控制
              [ApiController]
              [Route("api/[controller]/[action]")]
              public class WeatherForecastController : ControllerBase

          2.4.5 訪問地址

          http://localhost:5000/api/Test  //需要在headers里面增加 version: 1.1
          http://localhost:5000/api/WeatherForecast/Get 不受版本控制

          2.5 同時(shí)支持多種模式

          services.AddApiVersioning(o =>
          {
              o.ReportApiVersions = true;
              o.AssumeDefaultVersionWhenUnspecified = true;
              o.DefaultApiVersion = new ApiVersion(1, 0);
              o.ApiVersionReader = ApiVersionReader.Combine(new HeaderApiVersionReader("api-version"), new QueryStringApiVersionReader("api-version"));
              //或者
              //同時(shí)支持查詢字符串和標(biāo)頭
              o.ApiVersionReader = new QueryStringOrHeaderApiVersionReader(parameterName: "version"){HeaderNames = { "api-version""x-ms-version" }}
          });

          2.6 不借助包,封裝文件

          public class NameSpaceVersionRoutingConvention:IApplicationModelConvention
              {
                  private readonly string apiPrefix;
                  private const string urlTemplate = "{0}/{1}/{2}";
                  public NameSpaceVersionRoutingConvention(string apiPrefix = "api")
                  {
                      this.apiPrefix = apiPrefix;
                  }

                  public void Apply(ApplicationModel application)
                  {
                      foreach (var controller in application.Controllers)
                      {

                          var hasRouteAttribute = controller.Selectors
                          .Any(x => x.AttributeRouteModel != null);
                          if (!hasRouteAttribute)
                          {
                              continue;
                          }
                          var nameSpaces = controller.ControllerType.Namespace.Split('.');
                          //獲取namespace中版本號(hào)部分
                          var version = nameSpaces.FirstOrDefault(x => Regex.IsMatch(x, @"^v(\d+)$"));
                          if (string.IsNullOrEmpty(version))
                          {
                              continue;
                          }
                          string template = string.Format(urlTemplate, apiPrefix, version,
                          controller.ControllerName);
                          controller.Selectors[0].AttributeRouteModel = new AttributeRouteModel()
                          {
                              Template = template
                          };
                      }
                  }
              }

          調(diào)試代碼發(fā)現(xiàn)這種方式只在程序第一次運(yùn)行的時(shí)候會(huì)執(zhí)行,之后不會(huì)再執(zhí)行多次,因此效率很高。

          借鑒于:https://www.cnblogs.com/runningsmallguo/p/7484954.html

          參考文檔

          https://github.com/microsoft/aspnet-api-versioning







          回復(fù) 【關(guān)閉】學(xué)關(guān)
          回復(fù) 【實(shí)戰(zhàn)】獲取20套實(shí)戰(zhàn)源碼
          回復(fù) 【被刪】學(xué)個(gè)
          回復(fù) 【訪客】學(xué)
          回復(fù) 【小程序】學(xué)獲取15套【入門+實(shí)戰(zhàn)+賺錢】小程序源碼
          回復(fù) 【python】學(xué)微獲取全套0基礎(chǔ)Python知識(shí)手冊(cè)
          回復(fù) 【2019】獲取2019 .NET 開發(fā)者峰會(huì)資料PPT
          回復(fù) 【加群】加入dotnet微信交流群

          人人影視字幕組涼了,這款美劇APP不能錯(cuò)過!


          谷歌靈魂插件,98%的程序員都好評(píng)!


          瀏覽 72
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  国产综合在线视频 | 久草福利视频 | 牛牛AV国产一区二区 | 伊人青青亚洲 | 91在线观看欧美日韩 |