Strategies
1. URI
Each time we change the version, the clients will have to change the URL.
2. Via Query String
3. Via Headers
The client needs to have a developer who knows how to deal with headers, more sophisticated approach. Also we need to create our own custom header.
4. VIA ACCEPT HEADERS
Add the nuget package -- Microsoft.AspNetCore.Mvc.Versioning
[ApiVersion("1.0")]
[ApiVersion("1.1")]
[ApiVersion("2.0")]
public class WeatherForecastController : ControllerBase
Add this to the controller to let the user know what version it supports.
To the actions Specify these.
[HttpGet("sample")]
[MapToApiVersion("1.0")]
public IActionResult Getv1(string id) => Ok("Version 1");
[HttpGet("sample")]
[MapToApiVersion("1.1")]
public IActionResult Getv2() => Ok("Version 1.1");
[HttpGet("sample")]
[MapToApiVersion("2.0")]
public IActionResult GetV2() => Ok("Version 2");
When we call the API a string "Version 2 " is returned because we have set the Default Version to 2.0. This is still using QueryString to specify the version. If we try to request another version we will have to specify it in the query string.
https://localhost:44378/api/values/sample?api-version=1.0
Specify Versioning using a header
services.AddApiVersioning(op=> {
//Specify the default version for the API. Default routes that match this version will
// be invoked
op.DefaultApiVersion = new ApiVersion(2,0);
//If default version is not specified in the query string then
// we assume the above mentioned version as default.
op.AssumeDefaultVersionWhenUnspecified = true;
//Tell the user what all version that Api supports, will be added as a header.
op.ReportApiVersions = true;
//Add this to specify that the version will be passed as a header with
//the following key
op.ApiVersionReader = new HeaderApiVersionReader("X-Version");
// new QueryStringApiVersionReader();
});
Comments
Post a Comment