Effective API Versioning with Custom Middleware

Introduction

API versioning with custom middleware enables clients to access different versions of your API based on the version specified in the request header. This allows you to manage backward compatibility while rolling out new features or changes in a controlled manner. Custom middleware provides a central point for extracting and validating version information, making your versioning logic more modular and maintainable.

Step 1. Create a new ASP.NET Core Web API project using Visual Studio or the .NET CLI

First of All, you need to create ASP.NET Core Application using Visual Studio Or Using CLI Commands.

Step 2. Implement a custom middleware for API versioning.

using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

Author: Sardar Mudassar Ali Khan
public class ApiVersionMiddleware
{
    private readonly RequestDelegate _next;

    public ApiVersionMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        var apiVersion = context.Request.Headers["Api-Version"];

        if (!string.IsNullOrEmpty(apiVersion))
        {
            context.Items["ApiVersion"] = apiVersion;
        }

        await _next(context);
    }
}

Step 3. Configure the custom middleware and implement versioning in the controller

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

Author: Sardar Mudassar Ali Khan
public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        // Add versioning middleware
        services.AddTransient<ApiVersionMiddleware>();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        // Use the custom versioning middleware
        app.UseMiddleware<ApiVersionMiddleware>();

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

Step 4. Implement API versioning in the controller

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

Author: Sardar Mudassar Ali Khan
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private static List<string> _productsV1 = new List<string> { "Product A", "Product B" };
    private static List<string> _productsV2 = new List<string> { "New Product X", "New Product Y" };

    [HttpGet]
    public IActionResult Get()
    {
        var apiVersion = HttpContext.Items["ApiVersion"] as string;

        if (apiVersion == "v1")
        {
            return Ok(_productsV1);
        }
        else if (apiVersion == "v2")
        {
            return Ok(_productsV2);
        }
        else
        {
            return BadRequest("Invalid or missing API version.");
        }
    }
}

Step 5. API Versioning Testing

Test the API versioning using tools like Postman or a web browser. Set the API-Version header to specify the desired version, Like V1 OR V2

You have successfully implemented API versioning using custom middleware in your ASP.NET Core Web API. This approach allows you to manage different versions of your API, ensuring backward compatibility and smooth rollout of new features. The custom middleware centralizes the version extraction and validation process, making your versioning logic more organized and maintainable.

Conclusion

Managing API versioning is critical to building robust and adaptable APIs. The custom middleware-based approach demonstrated here empowers you to control API versions, ensuring both backward compatibility and seamless integration of new features. Let's summarize the key takeaways from this example:

Custom Middleware for API Versioning

  1. Custom middleware, such as the ApiVersionMiddleware, provides a centralized way to extract and validate API version information from incoming requests.
  2. Middleware intercepts incoming requests, allowing you to extract the version from request headers or other sources.
  3. Storing the version in the HttpContext.Items dictionary makes it accessible to downstream components, including the controllers.

Controller Implementation

  1. Controllers can access the API version information stored in HttpContext.Items to deliver responses tailored to the requested version.
  2. By checking the API version, you can provide different data or behavior for different versions of your API.

Benefits of Custom Middleware-Based Versioning

  1. Separation of concerns: Custom middleware encapsulates version extraction and validation, promoting clean and modular code.
  2. Centralized versioning logic: Middleware simplifies version management by handling this concern at a single point in the pipeline.
  3. Backward compatibility: Different API versions can coexist, ensuring that existing clients continue to receive expected responses while new versions are introduced.

Testing and Flexibility

  1. Testing: The custom middleware and version-specific logic can be thoroughly tested to ensure that API versioning behaves as expected.
  2. Flexibility: This approach accommodates different versioning schemes and strategies, allowing you to adapt the version extraction and validation logic as needed.

By employing custom middleware for API versioning, you're equipped to maintain a stable and adaptable API ecosystem. This methodology enables you to provide enhanced features to clients while honoring backward compatibility, ensuring a positive user experience, and allowing your application to evolve smoothly over time.