Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate Swagger.json file on build in .net 6.0?

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'.
like image 498
Sagar K Avatar asked Feb 01 '26 12:02

Sagar K


1 Answers

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


Add the following extension method
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

  • You can use SerializeAsYaml instead of SerializeAsJson if you want .yml file
  • You can specify the version of OpenAPI protocol by using Microsoft.OpenApi.OpenApiSpecVersion enum

If 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();
like image 62
Hakan Fıstık Avatar answered Feb 04 '26 02:02

Hakan Fıstık



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!