1️⃣ Why API Versioning Matters
Imagine you published a REST API for mobile apps:
-
Later you need a new field or change a parameter.
-
You can’t break old mobile apps that still call the old format.
API versioning lets you:
-
Publish new versions of your API
-
Keep old versions running until clients migrate.
2️⃣ Common Ways to Show the Version
You must tell the server which version the client wants.
Popular options:
Approach | Example call | Pros | Cons |
---|---|---|---|
URL path | /api/v1/products | Very clear, cache friendly | URL changes with every version |
Query string | /api/products?api-version=1.0 | Easy to test | Less obvious in logs |
HTTP header | GET /api/products + x-api-version:1.0 | Clean URLs | Harder to debug in browser |
Accept header (media type) | Accept: application/json; v=1.0 | Follows REST best practice | Requires custom header setup |
You can even combine them.
3️⃣ Official Microsoft Library
Use the NuGet package:
This library makes versioning easy.
4️⃣ Basic Setup (Path-based Versioning)
1. Install Package
2. Configure in Program.cs
(or Startup.cs
)
-
AssumeDefaultVersionWhenUnspecified: if client doesn’t pass a version, use default (1.0).
-
ReportApiVersions: tells clients which versions are available.
3. Version Your Controllers
Add a second version:
Now clients call:
5️⃣ Query-String Versioning
If you prefer ?api-version=1.0
:
Then the route can simply be [Route("api/[controller]")]
.
Clients call:
6️⃣ Header-Based Versioning
Client adds header:
7️⃣ Multiple Versions in One Controller
You can keep both actions in the same file:
8️⃣ Deleting or Deprecating Versions
Mark an old version as deprecated:
The response header api-deprecated-versions
warns clients.
9️⃣ Best Practices
-
Choose one clear versioning style and stick to it.
-
Document which versions exist and when they’ll be retired.
-
Use semantic versioning (1.0, 1.1, 2.0) to show backward compatibility.
-
Automate tests for every active version.
-
When possible, design for backward compatibility to avoid breaking clients.
🔟 Quick Flow Recap
-
Client requests with a version (URL / query / header).
-
ASP.NET Core checks the version using the configured reader.
-
The correct controller/action for that version executes.
-
Response headers tell the client which versions are supported.
🧠Key Takeaways
-
API versioning keeps old clients working while you release improvements.
-
Microsoft.AspNetCore.Mvc.Versioning makes it almost plug-and-play.
-
Pick a strategy (URL path, query, or header) and stay consistent.
-
Mark old versions as deprecated before removal.