Search code examples
asp.net-coreswashbuckle.aspnetcore

Is it possible to expose the same Swagger JSON in both Swagger 2.0 and Open API 3 formats with Swashbuckle in ASP .NET Core?


We have a legacy application that only works with Swagger 2.0 JSON format. For everything else we would like to use Open API format.

Is there any way with Swashbuckle .NET Core to expose JSON in different formats under separate URLs? It looks like the SerializeAsV2 property in the UseSwagger method options is global for all endpoints.

Basically I would like to have the following end points that contain the same API data in different formats.

/swagger/v1/openapi/swagger.json
/swagger/v1/swagger2/swagger.json

Solution

  • An alternative approach is to split the request pipeline:

    // serve v3 from /swagger/v1/swagger.json
    app.UseSwagger(o => o.RouteTemplate = "swagger/{documentName}/swagger.json");
    
    // serve v2 from /swagger2/v1/swagger.json
    app.Map("/swagger2", swaggerApp => 
        swaggerApp.UseSwagger(options => {
            // note the dropped prefix "swagger/"
            options.RouteTemplate = "{documentName}/swagger.json";
            options.SerializeAsV2 = true;
        })
    );