Versioning Using Custom Media Types - (Web API Versioning)
Versioning is an important concept in web API development, as it enables the API to evolve over time while maintaining compatibility with existing clients. Custom media types are a powerful tool for versioning web APIs, as they enable clients to request specific versions of the API based on their media type.
Syntax
To implement custom media type versioning in Web API, you will need to use the Accept
header in your HTTP requests and responses, and create custom media types to represent your API versions. Here is an example of a custom media type to represent version 1.0 of your API:
application/vnd.mycompany.myapi.v1+json
Example
Here is an example of how to implement custom media type versioning in Web API:
[Produces("application/vnd.mycompany.myapi.v1+json")]
[Route("api/[controller]")]
public class MyController : Controller
{
[HttpGet("{id:int}")]
public IActionResult Get(int id)
{
// Return API version 1.0 data
return Ok(new { Id = id, Name = "John Doe" });
}
}
public class CustomMediaTypeVersioning : MediaTypeVersioning
{
public CustomMediaTypeVersioning()
{
AddSupportedMediaType("application/vnd.mycompany.myapi.v1+json", "1.0");
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddMvcOptions(options =>
{
options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()));
options.InputFormatters.Add(new XmlSerializerInputFormatter());
options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
options.OutputFormatters.Add(new JsonOutputFormatter());
})
.AddVersionedApiExplorer(opts =>
{
opts.GroupNameFormat = "'v'VVV";
opts.SubstituteApiVersionInUrl = true;
});
services.AddApiVersioning(options =>
{
options.ApiVersionReader = new MediaTypeApiVersionReader("v");
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
options.ReportApiVersions = true;
options.Conventions.Controller<MyController>()
.HasApiVersion(new ApiVersion(1,