This post is about how to enable and use Open API for ASP.NET Core Web API with versioning enabled. I have created a Web API project in ASP.NET Core 5.0, so Open API is enabled by default. Next I am adding the Microsoft.AspNetCore.Mvc.Versioning package to enable versioning support. And I am enabling version support using the following code in Startup.cs - ConfigureServices method.
Next I am adding following code to enable version support in controller.
This will display something like this.
In the Open API UI, you need to pass the version as the parameter. It is not a good practice. To fix this we need to implement two Open API filters, one to remove the version text box from the UI and one to replace version information in the Open API document paths. So here is the first filter implementation which will remove the version textbox from Open API UI.
And you can use this class in ConfigureServices like this.
And if you run the application now, you will be able to see something like this - the version parameter got removed.
Now let me implement the document filter, which will replace the version in the URL path with the API version.
And similar to the RemoveVersionFromParameter class, you can use this class in ConfigureServices method, in the AddSwaggerGen method like this.
Now when you run the application you will be able to see something like this.
You will be able to see the {version} value removed from the URL and it is replaced with the version value. Next we will add another version for the Web API controller and an associated method, like this.
This controller supports two versions 1.0 and 2.0 and a method which supported only in 2.0 - which returns 10 days forecast instead of 5 days. And if you run the application you won’t be able to see version 2.0. Because even though we created version 2.0 of API we didn’t added the Open API information about 2.0 in the startup code. We can modify the ConfigureServices method like this.
And modify the Configure method like this.
If you run the application now, you will be able to see like this.
When you select the 2.0 version you can try out the Weather Forecast method which returns 10 days forecast. You can find the source code of this blog post on GitHub.