ASP.NET Core › Endpoint Metadata, Route Constraints & Templates

How would you implement route-based API versioning using route templates and constraints without a dedicated versioning library?

Advanced

Answer

A hand-rolled approach embeds the version directly in the route template ({version} segment, potentially constrained to a specific set of allowed values via a custom constraint or regex constraint) and dispatches to different handler logic based on the captured version value -- while workable for simple cases, this reimplements much of what a dedicated library like Asp.Versioning already provides more robustly (deprecation headers, Swagger integration), so it's generally only justified for very simple versioning needs.
app.MapGet("/api/v{version:regex(^(1|2)$)}/products/{id}", (string version, int id) => {
    return version == "2" ? GetProductV2(id) : GetProductV1(id);
});
Real-world example A small internal API implements minimal hand-rolled route-based versioning using a regex constraint restricting the version segment to '1' or '2', appropriate for its narrow, simple versioning needs without pulling in a full versioning library's overhead.

Common follow-ups: At what point does hand-rolled versioning become worth replacing with a dedicated library like Asp.Versioning?;How does this approach handle version-specific Swagger documentation?