ASP.NET Core Web API with Swagger API Versioning for dotnet 8
Tags: api, aspnet, swagger
Published: 2024-03-14 02:56:25

> ## Abstract
>
> In this article, we will explore how to implement URL-based API version control in ASP.NET Core Web API and integrate version control with Swagger using the `Asp.Versioning.Mvc` and `Asp.Versioning.Mvc.ApiExplorer` NuGet packages. This versioning mechanism not only helps maintain old versions of the API while introducing changes in new versions but also provides clear documentation and a testing interface for different versions of the API through Swagger UI.

## Introduction

As web applications evolve and change, API versioning becomes an essential consideration. It allows developers to introduce incompatible API changes without breaking existing client implementations. Implementing version control in ASP.NET Core Web API can keep your app flexible and scalable.

## How to Implement URL-Based API Version Control in ASP.NET Core Web API

URI version control is achieved by embedding the version information directly into the URL, making it a commonly used scheme in many API designs due to its intuitiveness and ease of understanding.

### Step 1: Install the Required NuGet Packages

To implement URL-based API version control, the first step is to install the `Asp.Versioning.Mvc` NuGet package. Note that the `Microsoft.AspNetCore.Mvc.Versioning` package used before dotnet 5 has been deprecated.

```bash
dotnet add package Asp.Versioning.Mvc --version 8.0.0
```

### Step 2: Configure Version Control

Configure version control in `Program.cs` or `Startup.cs` to enable API version reporting. This allows clients to know which versions of the API the server supports.

```csharp
builder.Services.AddApiVersioning(options =>
{
    options.ReportApiVersions = true;
});
```

### Step 3: Add Version Information to Controllers

Specify API version information on the controller to ensure the API access path includes the version number.

```csharp
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // ...
}
```

This way, clients can access a specific version of the API through URLs like `api/v1/values`.

## Integrating Version Control into Swagger

Integrating API version control into Swagger not only provides interface documentation but also allows testing different versions of the API through Swagger UI.

### Step 1: Install the Swagger Integration Package

First, install the Swagger package that integrates with API version control.

```bash
dotnet add package Asp.Versioning.Mvc.ApiExplorer --version 8.0.0
```

### Step 2: Configure Swagger to Support API Version Control

Configure API version control and Swagger integration in `Program.cs` to ensure there is a Swagger document for each version of the API.

```csharp
builder.Services.AddApiVersioning(
    options =>
    {
        options.ReportApiVersions = true;
    })
.AddApiExplorer(
    options =>
    {
        options.GroupNameFormat = "'v'VVV";
        options.SubstituteApiVersionInUrl = true;
    });
```

### Step 3: Configure Swagger UI to Display Different Versions of the API

Through the `ConfigureSwaggerOptions` class and `SwaggerGenOptions`, add a Swagger document for each discovered API version and display these versions in Swagger UI.

```csharp
public class ConfigureSwaggerOptions : IConfigureOptions<SwaggerGenOptions>
{
    private readonly IApiVersionDescriptionProvider _provider;

    public ConfigureSwaggerOptions(IApiVersionDescriptionProvider provider)
    {
        _provider = provider;
    }

    public void Configure(SwaggerGenOptions options)
    {
        foreach (var description in _provider.ApiVersionDescriptions)
        {
            options.SwaggerDoc(description.GroupName, CreateInfoForApiVersion(description));
        }
    }

    private OpenApiInfo CreateInfoForApiVersion(ApiVersionDescription description)
    {
        var info = new OpenApiInfo
        {
            Title = "API Title",
            Version = description.ApiVersion.ToString(),
            Description = "API Description. This API version has been deprecated."
        };

        return info;
    }
}

builder.Services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>();
```

Finally, enable Swagger in `Startup.cs` and configure Swagger UI to display endpoints for different versions of the API.

```csharp
app.UseSwagger();
app.UseSwaggerUI(
    options =>
    {
        var descriptions = app.DescribeApiVersions();

        foreach (var description in descriptions)
        {
            options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
        }
    });
```

## Conclusion

Through the above steps, we not only implemented URL-based API version control, but also successfully integrated it into Swagger, thereby providing clear, easy-to-access documentation and testing interfaces for different versions of the API. This approach ensures the long-term maintainability and backward compatibility of the API, while also improving the developer and end-user experience.