Khi một dịch vụ Web API được công khai, các ứng dụng client khác nhau bắt đầu sử dụng dịch vụ. Khi nghiệp vụ phát triển và yêu cầu thay đổi, ta có thể phải thay đổi dịch vụ, nhưng các thay đổi nên được thực hiện sao cho không làm hỏng các ứng dụng client hiện có.
Đây là lúc phiên bản hóa Web API giúp ích. Ta giữ nguyên các dịch vụ hiện có để không làm hỏng client cũ, và phát triển phiên bản mới của dịch vụ cho client mới sử dụng.
Một trong các tùy chọn triển khai phiên bản hóa là sử dụng URI. Dưới đây là ví dụ cách triển khai.
Ví dụ
Xét phiên bản 1 (V1) của student controller với các phương thức hành động sau.
Student Model V1
namespace DemoWebApplication.Models
{
public class StudentV1
{
public int Id { get; set; }
public string Name { get; set; }
}
}
Student Controller V1
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DemoWebApplication.Controllers
{
public class StudentV1Controller : ApiController
{
List students = new List
{
new StudentV1 { Id = 1, Name = "Mark" },
new StudentV1 { Id = 2, Name = "John" }
};
[Route("api/v1/students")]
public IEnumerable Get()
{
return students;
}
[Route("api/v1/students/{id}")]
public StudentV1 Get(int id)
{
var studentForId = students.FirstOrDefault(x => x.Id == id);
return studentForId;
}
}
}
Trong ví dụ trên, ta sử dụng Attribute Routing để triển khai phiên bản hóa. Kết quả:


Giả sử nghiệp vụ đề xuất thay đổi mới chỉ cho user mới, user cũ vẫn dùng V1. Ta giới thiệu Phiên bản 2 (V2).
Student Model V2
namespace DemoWebApplication.Models
{
public class StudentV2
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
Student Controller V2
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DemoWebApplication.Controllers
{
public class StudentV2Controller : ApiController
{
List students = new List
{
new StudentV2 { Id = 1, FirstName = "Roger", LastName = "Federer" },
new StudentV2 { Id = 2, FirstName = "Tom", LastName = "Bruce" }
};
[Route("api/v2/students")]
public IEnumerable Get()
{
return students;
}
[Route("api/v2/students/{id}")]
public StudentV2 Get(int id)
{
var studentForId = students.FirstOrDefault(x => x.Id == id);
return studentForId;
}
}
}
Kết quả
Kết quả của ví dụ trên:

