How do you combine multiple version reader strategies (e.g., both URL segment AND header) to give clients flexibility in how they specify a version?
Short answer
ApiVersionReader.Combine(reader1, reader2, ...) lets you accept a version from multiple sources simultaneously, checking each in order until one provides a value -- useful for supporting legacy clients using one convention (like a header) while newer clients migrate to a…
Advertisement
AModel answer
ApiVersionReader.Combine(reader1, reader2, ...) lets you accept a version from multiple sources simultaneously, checking each in order until one provides a value -- useful for supporting legacy clients using one convention (like a header) while newer clients migrate to a preferred convention (like URL segments), though care must be taken to define clear precedence if a request somehow specifies conflicting versions via different readers.
builder.Services.AddApiVersioning(options => {
options.ApiVersionReader = ApiVersionReader.Combine(
new UrlSegmentApiVersionReader(),
new HeaderApiVersionReader("X-Api-Version")
);
});
// Accepts either /api/v2/products OR /api/products with X-Api-Version: 2.0 headerReal-world example
An API supporting both a legacy internal tool (using an X-Api-Version header convention established years ago) and new public consumers (expecting modern URL-segment versioning) accepts both simultaneously during a gradual internal migration period.
Likely follow-ups
- What happens if a request specifies conflicting versions via two different readers?
- When would you want to restrict this back to a single reader for clarity?
Related topics