.netcore2.1 接口添加api-version版本控制


  • 使用Guget 添加Microsoft.AspNetCore.Mvc.Versioning 包引用,由於我的.netcore是2.1版本,避免出現不兼容問題,版本添加我選的也是2.1版本

  • 在Startup.cs中的  public void ConfigureServices(IServiceCollection services)添加如下代碼
 services.AddApiVersioning(o =>
            {
                o.ReportApiVersions = true;
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = new ApiVersion(2, 0); //設置默認版本
                //在請求頭(HTTP Header)中使用版本控制,在查詢字符串中指定版本號的方式將不再可用
                // o.ApiVersionReader = new HeaderApiVersionReader("x-api-version");
                o.ApiVersionReader = ApiVersionReader.Combine(new QueryStringApiVersionReader(), //同時支持(HTTP Header)中使用版本控制,和查詢字符串中指定版本號
                new HeaderApiVersionReader() { HeaderNames = { "x-api-version" } });
            });

 

  • 創建ValueV1和ValueV2兩個測試控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace WebApiVersion.Controllers
{
    [ApiVersion("1.0",Deprecated =true)]
    [Route("api/values")]
    [ApiController]
    public class ValuesV1Controller : ControllerBase
    {
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "Value1 from Version 1", "value2 from Version 1" };
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace WebApiVersion.Controllers
{
    [ApiVersion("2.0")]
    [Route("api/values")]
    [ApiController]
    public class ValuesV2Controller : ControllerBase
    {
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1 from Version 2", "value2 from Version 2" };
        }
    }
}

 

  • 接口默認返回設置的為2.0,現在請求1.0接口,使用Header方式

  • 使用查詢字符串方式請求

  • 使用ApiVersionNeutral指定不需要版本控制的Api
    [ApiVersionNeutral]
    [Route("api/[controller]")]
    [ApiController]
    public class HealthCheckController : ControllerBase
    {
        public string Get()
        {
            return "Good";
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM