web-api
  1. web-api-versioning-using-accept-header

Versioning Using Accept Header - (Web API Versioning)

API versioning is an important concept in web API development. It allows clients to use a specific version of a web API and thus prevents problems with compatibility and backward compatibility. In Web API Versioning, the Accept header is commonly used for versioning.

Syntax

To version a Web API using the Accept header in ASP.NET, you need to define the API version and add it to the Accept header of the request. To define the API version, you will need to use the ApiVersionAttribute class as shown below:

[ApiVersion("1.0")]
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
public class MyController : ControllerBase
{
   // Controller actions here
}

Once you have defined the API version, you can use the ProducesResponseType attribute on an action method to specify which version of the response to send back:

[HttpGet]
[ProducesResponseType(typeof(string), (int)HttpStatusCode.OK)]
[ApiVersion("1.0")]
public IActionResult GetV1()
{
    return Ok("Version 1.0");
}

Example

Here is an example of how to version a Web API using the Accept header in ASP.NET:

[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
   [HttpGet(Name = nameof(Get))]
   [ApiVersion("1.0")]
   [Produces("application/json")]
    public IActionResult Get()
    {
        return Ok(new { message = "This is version 1.0" });
    }

   [HttpGet(Name = nameof(Get))]
   [ApiVersion("2.0")]
   [Produces("application/json")]
    public IActionResult Get()
    {
        return Ok(new { message = "This is version 2.0" });
    }
}

Output

When a client sends a request to the above APIs using the Accept header, they will receive a JSON response that corresponds to the version they requested. For example:

GET /api/my HTTP/1.1
Host: localhost:5001
Accept: application/json; version=1.0

HTTP/1.1 200 OK
Content-Type: application/json
{
    "message": "This is version 1.0"
}

Explanation

In

Published on: