I want to generate Swagger.Json file on build and use it in API gateway to configure the endpoints.
I have tried following steps but its not working.
Create a tool manifest:
dotnet new tool-manifest
Install the Swashbuckle CLI tool and add it to the local manifest file: But this step fails
dotnet tool install --version 6.4.0 Swashbuckle.AspNetCore.Cli
Error :
NU1202: Package Swashbuckle.AspNetCore.Cli 6.4.0 is not compatible with net6.0 (.NETCoreApp,Version=v6.0). Package Swashbuckle.AspNetCore.Cli 6.4.0 supports:
- net5.0 (.NETCoreApp,Version=v5.0) / any
- net6.0 (.NETCoreApp,Version=v6.0) / any
- netcoreapp2.1 (.NETCoreApp,Version=v2.1) / any
- netcoreapp3.0 (.NETCoreApp,Version=v3.0) / any
NU1212: Invalid project-package combination for Swashbuckle.AspNetCore.Cli 6.4.0. DotnetToolReference project style can only contain references of the DotnetTool type
NU1212: Invalid project-package combination for Swashbuckle.AspNetCore.Cli 6.4.0. DotnetToolReference project style can only contain references of the DotnetTool type
Package 'Swashbuckle.AspNetCore.Cli 6.4.0' has a package type 'DotnetTool' that is not supported by project 'WebApi'.
This solution is ONLY for Swashbuckle V5 or newer.
See my other solution below for version V4 and older.
See my, yet, another solution below if you want to do this while building the project instead of doing that in the code.
See my, yet, another solution if you are using Microsoft.AspNetCore.OpenApi
using Microsoft.OpenApi.Extensions;
using Swashbuckle.AspNetCore.Swagger;
public static class SwaggerExtensions
{
public static void SaveSwaggerJson(this IServiceProvider provider)
{
ISwaggerProvider sw = provider.GetRequiredService<ISwaggerProvider>();
OpenApiDocument doc = sw.GetSwagger("v1", null, "/");
string swaggerFile = doc.SerializeAsJson(Microsoft.OpenApi.OpenApiSpecVersion.OpenApi3_0);
File.WriteAllText("swaggerfile.json", swaggerFile);
}
}
a couple of notes
SerializeAsYaml instead of SerializeAsJson if you want .yml fileMicrosoft.OpenApi.OpenApiSpecVersion enumIf you are using the new ASP.NET Core template, you can call this method like this
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
...
WebApplication app = builder.Build();
...
app.Services.SaveSwaggerJson();
...
app.Run();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With