Asp.net-Web-Api

Swagger WebApi 在建構時創建 json

  • December 23, 2020

有沒有辦法在我的 web api 的建構任務期間創建 swagger json?我想使用 json 將其輸入程式碼生成器並生成打字稿定義文件。

任何幫助都非常受歡迎!

您可以像這樣使用NSwag命令行工具:

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

這將為給定 DLL 中的所有控制器生成一個 Swagger 規範。

欲了解更多資訊,請閱讀此頁面

我正在使用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>

引用自:https://stackoverflow.com/questions/33283071