- 在Startup.cs中的 public void ConfigureServices(IServiceCollection services)添加如下代碼
<code> 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" } });
});/<code>
- 創建ValueV1和ValueV2兩個測試控制器
<code>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" };
}
}
}/<string>/<code>
<code>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" };
}
}
}/<string>/<code>
- 接口默認返回設置的為2.0,現在請求1.0接口,使用Header方式
- 使用查詢字符串方式請求
- 使用ApiVersionNeutral指定不需要版本控制的Api
<code> [ApiVersionNeutral]
[Route("api/[controller]")]
[ApiController]
public class HealthCheckController : ControllerBase
{
public string Get()
{
return "Good";
}
}/<code>
閱讀更多 愛踢狂人 的文章
關鍵字: AspNetCore Microsoft 版本