Using OpenApiReference, how to configure code generator options using a .nswag json options file (or any alternative)
Asked Answered
S

2

9

Context

I've added a connected service to my .NET 6 project and using NSwagCSharp code generator to generate the client. (In my previous project I used NSwagStudio)

I discovered that in the .csproj file there is a possibility to add options:

<OpenApiReference Include="OpenAPIs\swagger.json" CodeGenerator="NSwagCSharp" ClassName="MyClient">
  <SourceUri>https://localhost:xxxx/swagger/v1/swagger.json</SourceUri>
  <Options>/UseBaseUrl:false /GenerateClientInterfaces:true /InjectHttpClient:false, /DisposeHttpClient:false,
  </Options>
</OpenApiReference>

It seems those options are very same what NSwagStudio saves to its .nswag file. I am not sure this is only a guess, some of the them seems working so far. (is this documented somewhere?)

However NSwagStudio saves the default values too, (what I do no know what are) so in a typical .nswag file there are approx 80 settings in json:

"codeGenerators": {
 "openApiToCSharpClient": {
  ...
  "generateClientInterfaces": true,
  "clientBaseInterface": null,
  ... up to more than 80 lines...

Question

This would result a very long line in <Options> element in the .csproj file. (It seems line breaks not allowed(?) within). Is there any way to use an external options file like the json .nswag file to configure code generation options?

Scumble answered 20/11, 2021 at 7:55 Comment(0)
M
5

It appears that you can use XML CDATA sections to break up the options line, as an alternative to an external NSwag file:

<OpenApiReference Include="OpenAPIs\Membership.json" CodeGenerator="NSwagCSharp" Namespace="Membership">
    <SourceUri>https://example.org/schemata/membership/openapi.json</SourceUri>
    <Options>
        <![CDATA[/AdditionalNamespaceUsages:Membership.Common ]]>
        <![CDATA[/GenerateExceptionClasses:false ]]>
        <![CDATA[/OperationGenerationMode:SingleClientFromPathSegments ]]>
        <![CDATA[/JsonLibrary:SystemTextJson ]]>
    </Options>
</OpenApiReference>

It's only slightly better than a single, very long line.

Melany answered 28/11, 2023 at 23:37 Comment(0)
R
0

I believe you can achieve that by using the .nswag file you mentioned and following the schema from here:

https://github.com/RicoSuter/NSwag/wiki/NSwag-Configuration-Document

Rowney answered 11/10, 2023 at 6:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.