Search code examples
asp.net-coreswaggerasp.net-core-webapirestful-urlapi-versioning

Versioning with WebAPI .Net Core does not work as expected


I am trying to introduce URL versioning into my .Net Core WebAPI application. I am also using Swagger web tools for ease of use for users.

Now, while trying to introduce versioning into my application, I referenced the docs here: https://github.com/Microsoft/aspnet-api-versioning/wiki/New-Services-Quick-Start#aspnet-core

Now, I made following code changes into my code:

Startup.cs/ConfigureServices I added code below:

services.AddApiVersioning(options => {
                    options.AssumeDefaultVersionWhenUnspecified = true;
                });

Now, my controller annotations before any kind of versioning was added, looked like below:

    [Produces("application/json")]
    [Route("api/controllerName")]

and produces a URL which looks like something below:

http://localhost:12003/swagger/#!/Workspace/GetAll

Now, I added annotations below to enable api versioning:

. [ApiVersion("1.0")] [Produces("application/json")] [Route("api/v{version:apiVersion}/workspace")]

and now when I click on the same method listed in my swagger UI

the url looks like below:

http://localhost:12003/swagger/#!/controllername/ApiV_versionGetAll

While what I was expecting was something like:

http://localhost:12003/swagger/#!/controllername/V1.0/GetAll

Also on my swagger it is now asking me explicitly about entering version number. So I think my question boils down to two major points:

  • How I can I fix my URL? and what am I doing wrong?
  • Why is swagger now asking me to enter version number in API UI when I have explicitly stated that the version is going to be 1.0 in the annotation of the controller?

Solution

  • Setting up api versioning with swagger is indeed a tricky thing as it is lot's of pieces that need to be setup correctly.

    Luckily for us, there's a great nuget packages called SwashbuckleAspNetVersioningShim which solves this in an excellent way.

    Add it

    Install-Package SwashbuckleAspNetVersioningShim -Version 2.2.1
    

    Then follow the readme here