Swagger WebApi create json on build

You can use the NSwag command line tools like this:

nswag.exe webapi2swagger /assembly:"path/to/assembly.dll" /output:"path/to/swagger.json"

This generates a Swagger specification with for all controllers in the given DLL.

For more information read this page.


I'm using Swashbuckle.AspNetCore.Cli (note: I'm using .NET Core 3.1) https://github.com/domaindrivendev/Swashbuckle.AspNetCore

Add the following packages:

<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc5" />
<PackageReference Include="Swashbuckle.AspNetCore.Newtonsoft" Version="5.3.1" />
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="5.3.1" />

Next, create a tool manifest:

dotnet new tool-manifest

Install the Swashbuckle CLI tool and add it to the local manifest file:

dotnet tool install --version 5.3.1 Swashbuckle.AspNetCore.Cli

Now you can use a dotnet command to generate a swagger.json file. For example:

dotnet swagger tofile --output api.json bin/debug/netcoreapp3.1/xxx.yourApi.dll v1

If you want the file to be generated on each build, use a PostBuild target in your csproj file.

<Target Name="PostBuild" AfterTargets="PostBuildEvent">
    <Exec Command="dotnet tool restore" />
    <Exec Command="dotnet swagger tofile --output swagger.json $(OutputPath)\$(AssemblyName).dll v1 " />
</Target>