Previously I shared a solution about generics support in C# client generation from OpenAPI specification. In this article, I am going to show how to arrange API versioning and support it in C# client.


Before starting this article, I highly recommend visiting the previous one.

.ΝΕΤ versioning

First of all, we need our App with API versioning (NSwag wiki API versioning).

Startup class with changes:

namespace App
	{
	    public class Startup
	    {
	        ...

	        public void ConfigureServices(IServiceCollection services)
	        {
	            services
	                .AddApiVersioning(options =>
	                {
	                    options.AssumeDefaultVersionWhenUnspecified = true;
	                    options.DefaultApiVersion = new ApiVersion(1, 0);
	                })
	                .AddMvc();

	            services
	                .AddVersionedApiExplorer(options =>
	                {
	                    options.GroupNameFormat = "'v'VVV";
	                    options.SubstituteApiVersionInUrl = true;
	                });

	            // Add OpenAPI/Swagger documents
	            services
	                .AddOpenApiDocument(configure =>
	                {
	                    BaseConfigure(configure, "v1");
	                })
	                .AddOpenApiDocument(configure =>
	                {
	                    BaseConfigure(configure, "v2");
	                });
	        }

	        private void BaseConfigure(AspNetCoreOpenApiDocumentGeneratorSettings configure, string version)
	        {
	            configure.SchemaNameGenerator = new CustomSchemaNameGenerator();
	            configure.TypeNameGenerator = new CustomTypeNameGenerator();

	            configure.DocumentName = version;
	            configure.ApiGroupNames = new[] { version };

	            configure.PostProcess = document =>
	            {
	                document.Info.Version = version;
	                document.Info.Title = "App API";
	                document.Info.Description = "A simple ASP.NET Core web API";
	                document.Info.TermsOfService = "None";
	                document.Info.Contact = new OpenApiContact
	                {
	                    Name = "Renat Sungatullin",
	                    Email = string.Empty,
	                    Url = "some medium"
	                };
	            };
	        }

	        ...
	    }
	}

#code-generation #api-versioning #csharp #nswag #programming-c

C# client from multiple API versions using NSwag
23.90 GEEK