ASP.NET Core WebApi版本控制

前言:

 在平常項目開發中,隨着項目需求不斷的累加、不斷的迭代;項目服務接口須要向下兼容歷史版本;前些時候就由於Api接口爲作版本管理致使接口對低版本兼容處理不友好。git

 最近就像瞭解下如何實現WebApi版本控制,那麼版本控制有什麼好處呢?github

 WebApi版本控制的好處

  • 有助於及時推出功能, 而不會破壞現有系統,兼容性處理更友好。
  • 它還能夠幫助爲選定的客戶提供額外的功能。

 接下來就來實現版本控制以及在Swagger UI中接入WebApi版本web

1、WebApi版本控制實現

  經過Microsoft.AspNetCore.Mvc.Versioning 實現webapi 版本控制

  • 建立WebApi項目,添加Nuget包:Microsoft.AspNetCore.Mvc.Versioning 
Install-Package Microsoft.AspNetCore.Mvc.Versioning 
  • 修改項目Startup文件,使用Microsoft.AspNetCore.Mvc.Versioning 
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        //根據須要設置,如下內容
        services.AddApiVersioning(apiOtions =>
        {
            //返回響應標頭中支持的版本信息
            apiOtions.ReportApiVersions = true;
            //此選項將用於不提供版本的請求。默認狀況下, 假定的 API 版本爲1.0
            apiOtions.AssumeDefaultVersionWhenUnspecified = true;
            //缺省api版本號,支持時間或數字版本號
            apiOtions.DefaultApiVersion = new ApiVersion(1, 0);
            //支持MediaType、Header、QueryString 設置版本號;缺省爲QueryString、UrlSegment設置版本號;後面會詳細說明對於做用
            apiOtions.ApiVersionReader = ApiVersionReader.Combine(
                new MediaTypeApiVersionReader("api-version"),
                new HeaderApiVersionReader("api-version"),
                new QueryStringApiVersionReader("api-version"),
                new UrlSegmentApiVersionReader());
        });
        services.AddControllers();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseHttpsRedirection();

        //使用ApiVersioning
 app.UseApiVersioning();
app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints
=> { endpoints.MapControllers(); }); } }
  • WebApi設置版本:

  a)經過ApiVersion標記指定指定控制器或方法的版本號;Url參數控制版本(QueryStringApiVersionReader),以下:json

namespace WebAPIVersionDemo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    //Deprecated=true:表示v1即將棄用,響應頭中返回
    [ApiVersion("1.0", Deprecated = true)]
    [ApiVersion("2.0")]public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]{"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"};
 
        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = $"v1:{Summaries[rng.Next(Summaries.Length)]}"
            })
            .ToArray();
        }        
    }
}

  經過參數api-version參數指定版本號;調用結果:api

  

  b)經過Url Path Segment控制版本號(UrlSegmentApiVersionReader):爲控制器添加路由方式以下,apiVersion爲固定格式  app

[Route("/api/v{version:apiVersion}/[controller]")]

  調用方式:經過調用路徑傳入版本號,如:http://localhost:5000/api/v1/weatherforecastdom

   

  c)經過Header頭控制版本號:在Startup中設置(HeaderApiVersionReader、MediaTypeApiVersionReaderide

apiOtions.ApiVersionReader = ApiVersionReader.Combine(
                new MediaTypeApiVersionReader("api-version"),
                new HeaderApiVersionReader("api-version"));

   調用方式,在請求頭或中MediaType中傳遞api版本,以下:ui

   

    

  • 其餘說明:

    a)ReportApiVersions設置爲true時, 返回當前支持版本號(api-supported-versions);Deprecated 參數設置爲true表示已棄用,在響應頭中也有顯示(api-deprecated-versions):this

    

    b)MapToApiVersion標記:容許將單個 API 操做映射到任何版本(能夠在v1的控制器中添加v3的方法);在上面控制器中添加如下代碼,訪問v3版本方法

[HttpGet]
[MapToApiVersion("3.0")]
public IEnumerable<WeatherForecast> GetV3()
{
    //獲取版本
    string v = HttpContext.GetRequestedApiVersion().ToString();
    var rng = new Random();
    return Enumerable.Range(1, 1).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(-20, 55),
        Summary = $"v{v}:{Summaries[rng.Next(Summaries.Length)]}"
    })
    .ToArray();
}

    

    c)注意事項:

    一、路徑中參數版本高於,其餘方式設置版本

    二、多種方式傳遞版本,只能採用一種方式傳遞版本號

    三、SwaggerUI中MapToApiVersion設置版本不會單獨顯示    

2、Swagger UI中版本接入

 一、添加包:Swashbuckle.AspNetCore、Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer   

//swaggerui 包
Install-Package Swashbuckle.AspNetCore
//api版本
Install-Package Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer 

 二、修改Startup代碼:

public class Startup
{
    /// <summary>
    /// Api版本提者信息
    /// </summary>
    private IApiVersionDescriptionProvider provider;

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
          
        //根據須要設置,如下內容
        services.AddApiVersioning(apiOtions =>
        {
            //返回響應標頭中支持的版本信息
            apiOtions.ReportApiVersions = true;
            //此選項將用於不提供版本的請求。默認狀況下, 假定的 API 版本爲1.0
            apiOtions.AssumeDefaultVersionWhenUnspecified = true;
            //缺省api版本號,支持時間或數字版本號
            apiOtions.DefaultApiVersion = new ApiVersion(1, 0);
            //支持MediaType、Header、QueryString 設置版本號;缺省爲QueryString設置版本號
            apiOtions.ApiVersionReader = ApiVersionReader.Combine(
                    new MediaTypeApiVersionReader("api-version"),
                    new HeaderApiVersionReader("api-version"),
                    new QueryStringApiVersionReader("api-version"),
                    new UrlSegmentApiVersionReader());
        });


  services.AddVersionedApiExplorer(option => { option.GroupNameFormat = "接口:'v'VVV"; option.AssumeDefaultVersionWhenUnspecified = true; });  this.provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>(); services.AddSwaggerGen(options => { foreach (var description in provider.ApiVersionDescriptions) { options.SwaggerDoc(description.GroupName, new Microsoft.OpenApi.Models.OpenApiInfo() { Title = $"接口 v{description.ApiVersion}", Version = description.ApiVersion.ToString(), Description = "切換版本請點右上角版本切換" } ); } options.IncludeXmlComments(this.GetType().Assembly.Location.Replace(".dll", ".xml"), true); });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        //……    
   
        //使用ApiVersioning
        app.UseApiVersioning();

        //啓用swaggerui,綁定api版本信息
        app.UseSwagger(); app.UseSwaggerUI(c => { foreach (var description in provider.ApiVersionDescriptions) { c.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant()); } });

        //……    
    }
}

 三、運行效果:  

  

其餘: 

 示例地址:https://github.com/cwsheng/WebAPIVersionDemo

相關文章
相關標籤/搜索