Versioning Using Custom Header - (Web API Versioning)
Web API Versioning is an important aspect of developing and maintaining an API over time. One way to version your Web API is to use a custom header. This method allows you to include version information in every request and response, without modifying the URI or query string.
Syntax
To version your Web API using a custom header, you can add a version header to each request and response. Here is an example of how to add a version header:
[Route("api/mycontroller")]
public class MyController : Controller
{
[HttpGet]
public IActionResult Get()
{
var result = new { value = "Hello, world!" };
var version = "1.0";
Response.Headers.Add("X-Version", version);
return Ok(result);
}
}
Example
Here is an example of how to version your Web API using a custom header:
[Route("api/mycontroller")]
public class MyController : Controller
{
[HttpGet]
[MapToApiVersion("1.0")]
public IActionResult Get()
{
var result = new { value = "Hello, world!" };
var version = "1.0";
Response.Headers.Add("X-Version", version);
return Ok(result);
}
[HttpGet]
[MapToApiVersion("2.0")]
public IActionResult GetV2()
{
var result = new { message = "Hello, world!", date = DateTime.UtcNow };
var version = "2.0";
Response.Headers.Add("X-Version", version);
return Ok(result);
}
}
Output
When you call the versioned API using a custom header, you should see the version header in the response, like this:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
X-Version: 2.0
Date: Tue, 02 Feb 2021 20:58:04 GMT
Content-Length: 37
{"message":"Hello, world!","date":"2021-02-02T20:58:04.6031119Z"}
Explanation
In the example code, we define a Web API controller with two methods that have different map versions and responses. Each method includes a version header in the