如何配置NSwag.msbuild以使其跨平台构建net.core项目工作?

问题描述

我希望能够将nswag.json和swagger.json放入我的其余客户端项目中,并获得自动生成的CS代码

如果项目是最新的,也不要再次构建它。

解决方法

在您的csproj文件中,在结束标记之前添加以下代码

<PropertyGroup>
    <GeneratedClientsRoot>./*/</GeneratedClientsRoot>
    <GeneratedClientsWildcard>$(GeneratedClientsRoot)*.cs</GeneratedClientsWildcard>
</PropertyGroup>

<ItemGroup>
    <GeneratedClients Include="$(GeneratedClientsWildCard)" />
    <NSwagFiles Include="$(GeneratedClientsRoot)nswag.json" Condition="'@(GeneratedClients)' != ''" />
    <SwaggerFiles Include="$(GeneratedClientsRoot)swagger.json" Condition="'@(GeneratedClients)' != ''" />
</ItemGroup>

<Target Name="ForceGenerateClients" BeforeTargets="CoreCompile" Condition="'@(GeneratedClients)' == ''">
    <CallTarget Targets="GenerateClients" />
</Target>

<Target Name="AutoGenerateClients" BeforeTargets="CoreCompile" Inputs="@(NSwagFiles);@(SwaggerFiles)" Outputs="@(GeneratedClients)">
    <CallTarget Targets="GenerateClients" />
</Target>

<Target Name="GenerateClients">
    <Message Text="Generating swagger clients" Importance="high" />
    <ItemGroup Condition="'@(NSwagFiles)' == ''">
        <NSwagFiles Include="$(GeneratedClientsRoot)nswag.json" />
    </ItemGroup>
    <Exec Command="$(NSwagExe_Core31) run %(NSwagFiles.RelativeDir)%(NSwagFiles.Filename).json" />
    <ItemGroup>
        <NewClients Include="$(GeneratedClientsWildCard)" Exclude="@(GeneratedClients)" />
    </ItemGroup>
    <Message Text="Generated clients @(NewClients)" Importance="high" />
    <ItemGroup>
        <Compile Include="@(NewClients)" />
    </ItemGroup>
</Target>

第一个属性GeneratedClientsRoot是文件将存在的文件夹模式。如果为每个nswag.json创建一个文件夹,则需要使用默认的“ ./*/”。

例如,如果您想要项目根目录中的所有客户端,只需将GeneratedClientsRoot更改为“ ./”

上面的代码将在未创建客户端的情况下强制生成客户端,然后检测是否对nswag文件进行了更改并相应地重新生成客户端。

-编辑-添加了nswag.json配置示例

这是部分nswag.json配置,突出显示了重要的配置位。

{
    "runtime": "NetCore31","defaultVariables": null,"documentGenerator": {
        "fromDocument": {
            "json": "","url": "swagger.json","output": null
        }
    },"codeGenerators": {
        "openApiToCSharpClient": {
            "className": "MyRestServiceClient","namespace": "RestServices.MyRestService","output": "MyRestServiceClient.cs"
        }
    }
}

输出必须与nswag放在同一文件夹中。理想情况下,类名与文件名匹配,并且不要忘记名称空间。

-编辑2-先决条件

要使用此功能,您需要将块包nswag.msbuild添加到您的项目中。

将NSwagExe_Core31更改为NSwagExe_Core21或您使用的任何框架版本。 还要将nswag运行时更改为正确的运行时。