Nov 06 2023
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/products")]
public class ProductsV1Controller : ApiController
{
public IHttpActionResult Get()
{
// Implementation for version 1
}
}
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/products")]
public class ProductsV2Controller : ApiController
{
public IHttpActionResult Get()
{
// Implementation for version 2
}
}
public class QueryStringVersionController : ApiController
{
const string DefaultApiVersion = "1.0";
[HttpGet]
public IHttpActionResult Get()
{
var apiVersion = HttpContext.Current.Request.QueryString["version"] ?? DefaultApiVersion;
if (apiVersion == "1.0")
{
// Implementation for version 1
}
else if (apiVersion == "2.0")
{
// Implementation for version 2
}
else
{
return BadRequest("Version not supported");
}
}
}
public class HeaderVersionController : ApiController
{
private const string HeaderName = "X-API-Version";
[HttpGet]
public IHttpActionResult Get()
{
var apiVersion = HttpContext.Current.Request.Headers[HeaderName];
if (apiVersion == "1.0")
{
// Implementation for version 1
}
else if (apiVersion == "2.0")
{
// Implementation for version 2
}
else
{
return BadRequest("API version is required");
}
}
}
[Produces("application/json")]
public class MediaTypeVersionController : ApiController
{
[HttpGet]
public IHttpActionResult Get()
{
string apiVersion = GetApiVersionFromAcceptHeader();
if (apiVersion == "v1")
{
// Implementation for version 1
}
else if (apiVersion == "v2")
{
// Implementation for version 2
}
else
{
return BadRequest("API version is required");
}
}
private string GetApiVersionFromAcceptHeader()
{
var acceptHeader = Request.Headers.Accept.FirstOrDefault();
if (acceptHeader != null)
{
var versionParameter = acceptHeader.Parameters
.FirstOrDefault(p => p.Name.Equals("version", StringComparison.OrdinalIgnoreCase));
return versionParameter?.Value;
}
return null;
}
}
// This would be set up in your routing configuration or Web API configuration.
config.Routes.MapHttpRoute(
name: "Version1",
routeTemplate: "api-v1/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "Version2",
routeTemplate: "api-v2/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Join 13,250+ subscribers to improve your .NET Knowledge.
Go-to resource for understanding the core concepts of design patterns without the overwhelming complexity. In this concise and affordable ebook, I've distilled the essence of design patterns into an easy-to-digest format. It is a Beginner level. Check out it here.
Every Monday morning, I share 1 actionable tip on C#, .NET & Arcitecture topic, that you can use right away.
Subscribe to the TheCodeMan.net and be among the 13,250+ subscribers gaining practical tips and resources to enhance your .NET expertise.