Swagger WebApi 在构建时创建 json

Swagger WebApi create json on build

有什么方法可以在我的网站 api 的构建任务期间创建 swagger json?我想使用 json 将其输入代码生成器并生成打字稿定义文件。

非常欢迎任何帮助!

您可以像这样使用 NSwag 命令行工具:

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

这会为给定 DLL 中的所有控制器生成 Swagger 规范。

了解更多信息read this page

我正在使用 Swashbuckle.AspNetCore.Cli(注意:我正在使用 .NET Core 3.1) https://github.com/domaindrivendev/Swashbuckle.AspNetCore

添加以下包:

<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" />

接下来,创建一个工具清单:

dotnet new tool-manifest

安装 Swashbuckle CLI 工具并将其添加到本地清单文件:

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

现在您可以使用 dotnet 命令生成 swagger.json 文件。例如:

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

如果您希望在每次构建时生成该文件,请在您的 csproj 文件中使用 PostBuild 目标。

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