由于旧的Asp.Net Core WebAPI可能已经有很多其他地方在调用,新修改的API不应该影响到原来API的正常使用,所以需要进行API的版本控制。以下我们使用Microsoft Visual Studio Enterprise 2019创建ASP.NET Core 3.1项目(先安装ASP.NET Core 3.1环境)。
首先在Nuget中搜索Microsoft.AspNetCore.Mvc.Versioning
public void ConfigureServices(IServiceCollection services) {
...
services.AddApiVersioning(options => {
options.AssumeDefaultVersionWhenUnspecified = true;
});
}
新建一个DemoResponse.cs文件
namespace AspNetCoreVersioning.Contracts {
public class DemoResponseV1 {
public Guid Id {
get;
set;
}
public string Name {
get;
set;
}
}
public class DemoResponseV2 {
public Guid Id {
get;
set;
}
public string DemoName {
get;
set;
}
}
}
添加ApiVersioningDemoController.cs
namespace AspNetCoreVersioning.Controllers {
[ApiController]
[Route("api/demos")]
public class ApiVersioningDemoController: ControllerBase {
[HttpGet("{demoId}")]
public IActionResult GetDemo([FromRoute] Guid demoId) {
var demo = new DemoResponse {
Id = demoId,
Name = "api demo"
};
return Ok(demo);
}
}
}
namespace AspNetCoreVersioning.Controllers {
[ApiController]
[Route("api/demos")]
[ApiVersion("1.0")]
[ApiVersion("2.0")]
public class ApiVersioningDemoController: ControllerBase {
[HttpGet("{demoId}")]
public IActionResult GetDemoV1([FromRoute] Guid demoId) {
var demo = new DemoResponseV1 {
Id = demoId,
Name = "demo v1 "
};
return Ok(demo);
}
[HttpGet("{demoId}")]
[MapToApiVersion("2.0")]
public IActionResult GetDemoV2([FromRoute] Guid demoId) {
var demo = new DemoResponseV2 {
Id = demoId,
DemoName = "demo v2"
};
return Ok(demo);
}
}
}
运行测试
https://localhost.57327/api/demos/00000000-0000-0000-0000-000000000000?api-version=1
输出
Result: {"id":"00000000-0000-0000-0000-000000000000","name":"demo v1"}
https://localhost:57327/api/demos/00000000-0000-0000-0000-000000000000?api-version=2
Result: {"id":"00000000-0000-0000-0000-000000000000","demoName":"demo v2"}