Skip to content

About

API versioning in ASP.NET Core Web API: URL segment, query string, and header-based versioning strategies with per-version Swagger UI using the official Asp.Versioning NuGet package.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

1 Commit

Folders and files

Repository files navigation

dotnet-api-versioning-aspnetcore

API versioning in ASP.NET Core β€” URL segment, query string, and header strategies with Swagger per-version UI using the official Asp.Versioning package.

Visit CodingDroplets YouTube Patreon Buy Me a Coffee GitHub


πŸš€ Support the Channel β€” Join on Patreon

If this sample saved you time, consider joining our Patreon community. You'll get exclusive .NET tutorials, premium code samples, and early access to new content β€” all for the price of a coffee.

πŸ‘‰ Join CodingDroplets on Patreon

Prefer a one-time tip? Buy us a coffee β˜•


🎯 What You'll Learn

  • How to add API versioning to ASP.NET Core Web API using the official Asp.Versioning NuGet package
  • Three versioning strategies: URL segment (/api/v1/), query string (?api-version=1.0), and request header (X-Api-Version: 2.0)
  • How to set a default version so existing clients aren't broken
  • How to report supported and deprecated versions via response headers
  • How to configure Swagger/OpenAPI with one document per API version for a clean developer experience
  • How to evolve your API (v1 β†’ v2) without breaking existing consumers
  • How to write integration tests for versioned endpoints using WebApplicationFactory

πŸ—ΊοΈ Architecture Overview

HTTP Client
    β”‚
    β”œβ”€ GET /api/v1/products           ── URL Segment versioning
    β”œβ”€ GET /api/v1/products?api-version=1.0  ── Query String versioning
    β”œβ”€ GET /api/v1/products  + Header X-Api-Version: 1.0  ── Header versioning
    β”‚
    β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚              ASP.NET Core Pipeline               β”‚
β”‚                                                 β”‚
β”‚  ApiVersionReader (URL + QueryString + Header)  β”‚
β”‚         β”‚ resolves to ApiVersion(major, minor)  β”‚
β”‚         β–Ό                                       β”‚
β”‚  ApiVersioningMiddleware                        β”‚
β”‚         β”‚ routes to the correct controller      β”‚
β”‚         β–Ό                                       β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚ ProductsV1      β”‚ ProductsV2              β”‚  β”‚
β”‚  β”‚ Controller      β”‚ Controller              β”‚  β”‚
β”‚  β”‚ [ApiVersion     β”‚ [ApiVersion             β”‚  β”‚
β”‚  β”‚  ("1.0")]       β”‚  ("2.0")]               β”‚  β”‚
β”‚  β”‚                 β”‚                         β”‚  β”‚
β”‚  β”‚ GET /products   β”‚ GET /products           β”‚  β”‚
β”‚  β”‚ GET /products   β”‚ GET /products?category= β”‚  β”‚
β”‚  β”‚   /{id}         β”‚   /{id}                 β”‚  β”‚
β”‚  β”‚                 β”‚ GET /products/categoriesβ”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
         β–Ό
  Swagger UI (v1 doc + v2 doc dropdown)

πŸ“‹ Versioning Strategy Comparison

Strategy Example Request When to Use
URL Segment GET /api/v1/products Default choice β€” explicit, cacheable
Query String GET /api/v1/products?api-version=1.0 Easy for quick testing / scripts
Header GET /api/v1/products + X-Api-Version: 2.0 Clean URLs, internal/service-to-service APIs
API Version Model Fields Extra Endpoints
v1 Id, Name, Price None
v2 Id, Name, Price, Category, Stock GET /categories filter

πŸ“ Project Structure

dotnet-api-versioning-aspnetcore/
β”‚
β”œβ”€β”€ ApiVersioningDemo/                      # Main Web API project
β”‚   β”œβ”€β”€ Controllers/
β”‚   β”‚   β”œβ”€β”€ V1/
β”‚   β”‚   β”‚   └── ProductsV1Controller.cs    # [ApiVersion("1.0")] β€” basic product list
β”‚   β”‚   └── V2/
β”‚   β”‚       └── ProductsV2Controller.cs    # [ApiVersion("2.0")] β€” extended + category filter
β”‚   β”œβ”€β”€ Models/
β”‚   β”‚   β”œβ”€β”€ ProductV1.cs                   # Id, Name, Price
β”‚   β”‚   └── ProductV2.cs                   # Id, Name, Price, Category, Stock
β”‚   β”œβ”€β”€ Properties/
β”‚   β”‚   └── launchSettings.json            # Swagger opens automatically in Visual Studio
β”‚   β”œβ”€β”€ Program.cs                         # DI setup: versioning, Swagger, JSON options
β”‚   β”œβ”€β”€ appsettings.json
β”‚   └── ApiVersioningDemo.csproj
β”‚
β”œβ”€β”€ ApiVersioningDemo.Tests/               # xUnit integration tests
β”‚   β”œβ”€β”€ ProductsApiTests.cs                # 12 tests β€” URL, query string, header versioning
β”‚   └── ApiVersioningDemo.Tests.csproj
β”‚
β”œβ”€β”€ dotnet-api-versioning-aspnetcore.sln   # Solution file
└── README.md

πŸ› οΈ Prerequisites

Requirement Version
.NET SDK 10.0+
IDE (optional) Visual Studio 2022+, VS Code, or Rider

Check your SDK version:

dotnet --version

⚑ Quick Start

# 1. Clone the repository
git clone https://github.com/codingdroplets/dotnet-api-versioning-aspnetcore.git
cd dotnet-api-versioning-aspnetcore

# 2. Build the solution
dotnet build -c Release

# 3. Run the Web API
cd ApiVersioningDemo
dotnet run

# 4. Open Swagger UI in your browser
# http://localhost:5289/swagger

Swagger UI will open with a version dropdown β€” switch between v1 and v2 to explore each API independently.


πŸ”§ How It Works

1. Install the Packages

<PackageReference Include="Asp.Versioning.Http" Version="8.1.0" />
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="8.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.3.1" />

2. Configure API Versioning in Program.cs

builder.Services.AddApiVersioning(options =>
{
    options.DefaultApiVersion = new ApiVersion(1, 0);
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.ReportApiVersions = true;  // emits api-supported-versions header

    options.ApiVersionReader = ApiVersionReader.Combine(
        new UrlSegmentApiVersionReader(),           // /api/v1/products
        new QueryStringApiVersionReader("api-version"), // ?api-version=1.0
        new HeaderApiVersionReader("X-Api-Version")    // X-Api-Version: 2.0
    );
})
.AddApiExplorer(options =>
{
    options.GroupNameFormat = "'v'VVV";     // formats as v1, v2
    options.SubstituteApiVersionInUrl = true;
});

3. Annotate Controllers with [ApiVersion]

// V1 controller β€” serves /api/v1/products
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class ProductsController : ControllerBase { ... }

// V2 controller β€” serves /api/v2/products
[ApiController]
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class ProductsController : ControllerBase { ... }

4. Register Separate Swagger Docs per Version

builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo { Title = "API Demo", Version = "v1" });
    options.SwaggerDoc("v2", new OpenApiInfo { Title = "API Demo", Version = "v2" });
});

5. Configure Swagger UI with Both Endpoints

app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
    options.SwaggerEndpoint("/swagger/v2/swagger.json", "v2");
});

6. Evolve the API β€” v1 vs v2 Models

// v1 β€” simple
public class ProductV1
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public decimal Price { get; set; }
}

// v2 β€” extended (Category + Stock added without breaking v1)
public class ProductV2
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public decimal Price { get; set; }
    public string Category { get; set; } = string.Empty;
    public int Stock { get; set; }
}

πŸ“‘ API Endpoints

v1 Endpoints

Method Endpoint Description Status Codes
GET /api/v1/products Returns all products (basic) 200
GET /api/v1/products/{id} Returns product by ID 200, 404

v2 Endpoints

Method Endpoint Description Status Codes
GET /api/v2/products Returns all products (extended) 200
GET /api/v2/products?category=X Filter products by category 200
GET /api/v2/products/{id} Returns extended product by ID 200, 404
GET /api/v2/products/categories Returns distinct category list 200

Versioning Query String & Header

Method Example Description
GET /api/v1/products?api-version=1.0 Query string versioning
GET /api/v2/products?api-version=2.0 Query string versioning
GET /api/v1/products + X-Api-Version: 1.0 Header versioning

Response headers returned by all versioned endpoints:

api-supported-versions: 1.0, 2.0

πŸ§ͺ Running Tests

dotnet test -c Release

Test Summary:

Test Name Strategy Pass/Fail
V1_GetAll_Returns200_WithProducts URL Segment βœ… Pass
V1_GetById_ExistingId_Returns200 URL Segment βœ… Pass
V1_GetById_NonExistingId_Returns404 URL Segment βœ… Pass
V1_GetAll_ResponseContainsApiSupportedVersionsHeader URL Segment βœ… Pass
V2_GetAll_Returns200_WithExtendedProducts URL Segment βœ… Pass
V2_GetAll_FilterByCategory_ReturnsMatchingProducts URL Segment βœ… Pass
V2_GetById_ExistingId_Returns200_WithCategoryAndStock URL Segment βœ… Pass
V2_GetById_NonExistingId_Returns404 URL Segment βœ… Pass
V2_GetCategories_Returns200_WithDistinctCategories URL Segment βœ… Pass
QueryStringVersion_V1_Returns200 Query String βœ… Pass
QueryStringVersion_V2_Returns200 Query String βœ… Pass
HeaderVersion_V1_Returns200 Header βœ… Pass

Total: 12 tests β€” 12 passed βœ…


πŸ€” Key Concepts

Why Version Your API?

Problem (No Versioning) Solution (With Versioning)
Adding a field breaks existing clients Old clients keep using v1; new clients adopt v2
Removing a field causes runtime errors Deprecate v1 gradually; remove only after migration
Behaviour changes break integrations Each version is an isolated, stable contract

URL Segment vs Query String vs Header

Strategy Pros Cons
URL Segment Explicit, cacheable, easy to bookmark Changes URL structure
Query String No URL change, easy for testing Not REST-pure, can pollute query params
Header Clean URLs, good for service-to-service Less discoverable, harder to test in browser

Recommendation: Use URL segment as the primary strategy. Combine with query string and header for flexibility β€” exactly what this sample demonstrates.

ReportApiVersions = true

When enabled, every response includes:

api-supported-versions: 1.0, 2.0
api-deprecated-versions: (empty if none deprecated)

This is invaluable for clients to self-discover which versions are available.


🏷️ Technologies Used

Technology Purpose
.NET 10 / ASP.NET Core 10 Web API framework
Asp.Versioning v8 API versioning (URL, query string, header)
Asp.Versioning.Mvc.ApiExplorer Swagger integration for versioned docs
Swashbuckle.AspNetCore v7 Swagger / OpenAPI UI
xUnit v2 Unit and integration testing framework
WebApplicationFactory In-process integration test host

πŸ“š References


πŸ“„ License

This project is licensed under the MIT License.


πŸ”— Connect with CodingDroplets

Platform Link
🌐 Website https://codingdroplets.com/
πŸ“Ί YouTube https://www.youtube.com/@CodingDroplets
🎁 Patreon https://www.patreon.com/CodingDroplets
β˜• Buy Me a Coffee https://buymeacoffee.com/codingdroplets
πŸ’» GitHub http://github.com/codingdroplets/

Want more samples like this? Support us on Patreon or buy us a coffee β˜• β€” every bit helps keep the content coming!

About

API versioning in ASP.NET Core Web API: URL segment, query string, and header-based versioning strategies with per-version Swagger UI using the official Asp.Versioning NuGet package.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages