एक बार Web API सर्विस पब्लिक हो जाने के बाद, विभिन्न क्लाइंट एप्लिकेशन हमारी Web API सर्विसेज का उपयोग करना शुरू कर देते हैं। जैसे-जैसे व्यवसाय बढ़ता है और आवश्यकताएं बदलती हैं, हमें सर्विसेज को भी बदलना पड़ सकता है, लेकिन सर्विसेज में परिवर्तन इस तरह से किए जाने चाहिए कि कोई मौजूदा क्लाइंट एप्लिकेशन न टूटे।
यहीं पर Web API वर्जनिंग मदद करती है। हम मौजूदा सर्विसेज को वैसे ही रखते हैं, ताकि मौजूदा क्लाइंट एप्लिकेशन न टूटें, और सर्विस का एक नया वर्जन विकसित करते हैं जिसका नई क्लाइंट एप्लिकेशन उपयोग करना शुरू कर सकती हैं।
वर्जनिंग लागू करने के विकल्पों में से एक URI का उपयोग करना है। नीचे उसी को लागू करने का एक उदाहरण दिया गया है।
उदाहरण
आइए स्टूडेंट कंट्रोलर के वर्जन 1 (V1) पर विचार करें जिसमें निम्नलिखित एक्शन मेथड्स हैं।
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;
}
}
}
उपरोक्त उदाहरण में हमने वर्जनिंग लागू करने के लिए Attribute Routing का उपयोग किया है। उपरोक्त उदाहरण का आउटपुट नीचे दिखाया गया है:


अब मान लीजिए स्टूडेंट कंट्रोलर में, व्यवसाय ने केवल नए उपयोगकर्ताओं के लिए एक नया परिवर्तन प्रस्तावित किया है और मौजूदा उपयोगकर्ताओं को अभी भी वर्जन 1 का उपयोग करना चाहिए। इस मामले में हमें वर्जन 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;
}
}
}
आउटपुट
उपरोक्त उदाहरण का आउटपुट नीचे दिखाया गया है।

