เมื่อ Web API เปิดให้บริการสาธารณะ Client หลายๆ ตัวจะเริ่มใช้งาน เมื่อธุรกิจเติบโตและ Requirements เปลี่ยน เราอาจต้องเปลี่ยน Service แต่ต้องไม่ทำให้ Client เดิมเสียหาย → ต้องมี Versioning
วิธีหนึ่งคือใช้ URI แบบ Attribute Routing
Version 1 (V1)
// Model
namespace DemoWebApplication.Models
{
public class StudentV1
{
public int Id { get; set; }
public string Name { get; set; }
}
}
// Controller
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() => students;
[Route("api/v1/students/{id}")]
public StudentV1 Get(int id) => students.FirstOrDefault(x => x.Id == id);
}
}
ผลลัพธ์ V1:


Version 2 (V2) - ธุรกิจต้องการเปลี่ยนโครงสร้างข้อมูล
// Model V2
namespace DemoWebApplication.Models
{
public class StudentV2
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
// 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() => students;
[Route("api/v2/students/{id}")]
public StudentV2 Get(int id) => students.FirstOrDefault(x => x.Id == id);
}
}
ผลลัพธ์ V2:

