Reputation: 1119
I would like to be able to drop nswag.json and swagger.json in my rest clients project and get the cs code generated automatically.
Also if the project is up-to-date don't build it again.
Upvotes: 2
Views: 3335
Reputation: 1119
In your csproj file add the following code before the closing tag
<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>
The first property GeneratedClientsRoot is the folder pattern where your files will exist. If you create a folder for each nswag.json then the default "./*/" is what you need.
If for example you want all clients in the root of your project simply change GeneratedClientsRoot to "./"
The above code will force generate the clients if there are none created and then will detect if changes to nswag files have happened and regenerate clients accordingly.
--Edit - Added nswag.json config example
This is a partial nswag.json config highlighting important configuration bits.
{
"runtime": "NetCore31",
"defaultVariables": null,
"documentGenerator": {
"fromDocument": {
"json": "",
"url": "swagger.json",
"output": null
}
},
"codeGenerators": {
"openApiToCSharpClient": {
"className": "MyRestServiceClient",
"namespace": "RestServices.MyRestService",
"output": "MyRestServiceClient.cs"
}
}
}
Output needs to be in the same folder as the nswag. Ideally classname matches filename, and don't forget the namespace.
-- Edit 2 - Prerequisites
In order to use this you need to add nugget package nswag.msbuild to your project.
Change NSwagExe_Core31 to NSwagExe_Core21 or whatever framework version you are using. Also change nswag runtime to the correct runtime.
Upvotes: 1