How To: Multiple API versions in one codebase

You need to upgrade your current Web API to a new version and some consumers can not consume the new version. Existing consumers should be able to use the old versions and customers who can use the latest API version should be able to use the latest one. 

Requirements are, of course, using a single codebase to host both versions.

Requirements

Requirements for this How-To is just a working .Net Core Web API with working Swagger/OpenAPI UI.

Dependencies

We need to add the following nuget packages to our Web API project:

  • Swashbuckle.AspNetCore
  • Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer
  • Microsoft.ASpNetCore.Mvc.Versioning

Code changes

Changes in Controller

We need to make some changes for controller classes and actions within.

For the classes we will add some attributes regarding the version and the routing changes:

We need the below attributes for the actions, to route them correctly and use the correct functions for the execution:

Implement some classes for API explorer

We need to implement a custom filter, based on „IOperationFilter“ in the namespace „Swashbuckle.AspNetCore.SwaggerGen“:

After we implemented the filter, we need to to create a custom class for implementing the „IConfigureOptions“ Interface

Changes in Startup class

In the ConfigureServices method we need to implement some changes to initialize versioning for our API using our custom classes:

For the general Configure function we need to add a parameter for the api version description provider and implement some changes:

See results

Start our project now results in two API versions, as we declared with the attributes. Notice that the routing happens via the „VX“ in the url:

Legacy V1 API

New V2 API

Happy coding! 🙂

Leave a Comment

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.