Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gtechsltn/97813cebfc436e95a88dbed33dde0a44 to your computer and use it in GitHub Desktop.
Save gtechsltn/97813cebfc436e95a88dbed33dde0a44 to your computer and use it in GitHub Desktop.
Generate OpenApi.json on build from ASP.NET 8 Minimal API

To generate OpenApi.json on build from an ASP.NET 8 Minimal API, follow these steps:

  1. In Visual Studio for Windows 17.7.0 or later, create a new ASP.NET Core API project

  2. Follow these instructions to install Swashbuckle.AspNetCore.Cli as a local dotnet tool in your project

  3. Add these NuGet packages (or later versions) to the project:

  <ItemGroup>
  	<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0-preview.4.23260.4" />
  	<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
  </ItemGroup>
  1. Add this target to the .csproj file:
<!-- Generate openapi.json on build; see
     https://github.com/domaindrivendev/Swashbuckle.AspNetCore#using-the-tool-with-the-net-core-30-sdk-or-later -->
<Target Name="OpenAPI" AfterTargets="Build" Condition="$(Configuration)=='Debug'">
    <Exec Command="dotnet swagger tofile --output openapi.json $(TargetPath) v1" WorkingDirectory="$(TargetDir)" />
</Target>
  1. In Program.cs, add the OpenApi services:

    builder.Services.AddEndpointsApiExplorer()
                    .AddSwaggerGen();

    and append .WithOpenApi() to the MapGroup() statement:

    var todosApi = app.MapGroup("/todos").WithOpenApi();

    (optional) if you also want to generate the Swagger UI under the /swagger url, add:

    if (app.Environment.IsDevelopment()) _ = app.UseSwagger().UseSwaggerUI();
  2. Build the project; the build output will contain a line like:
    Swagger JSON/YAML successfully written to ...\bin\Debug\net8.0\openapi.json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment