NSwag generating duplicate types
Asked Answered
C

1

6

I am using NSwag SwaggerToCSharpClientGenerator to generate the request and response classes and enums.

I have some Web API methods that share the same enum as an argument or as part of request object. When I run the NSwag API, it generates the same enum definition multiple times, but named as Enum1, Enum2, Enum3, ResponseClassEnum.

Can I configure NSwag (or Swashbuckle) so that only one enum is generated?

My NSwag code looks like:

   var document = SwaggerDocument.FromUrlAsync(
      "http://localhost:5003/swagger/v1/swagger.json").Result;

   var settings = new SwaggerToCSharpClientGeneratorSettings();
   settings.GenerateClientClasses = false;
   settings.CSharpGeneratorSettings.Namespace = "My.Interface";
   settings.CSharpGeneratorSettings.ArrayType = "List";
   settings.AdditionalNamespaceUsages = new string[] { "System.Collections.Generic" };
   settings.GenerateExceptionClasses = false;

   var generator = new SwaggerToCSharpClientGenerator(document, settings);

   var code = generator.GenerateFile();
   File.WriteAllText("Swagger.MyApi.cs", code);

I have put obfuscated swagger.json here - https://pastebin.com/hT5ySZub

Produced output from obfuscated swagger.json is here - https://pastebin.com/e0AYJWer In the output, the type DupEnum is defined in types: DupEnum, DupEnum2, DupEnum3, and TypeBDupEnum.

Chubby answered 16/9, 2017 at 18:42 Comment(0)
K
7

You are probably generating the swagger spec with swashbuckle: The problem is that Swashbuckle does not reference enums but repeats them - this is why they are generated multiple times (see: https://github.com/RSuter/NJsonSchema/issues/17).

If the spec is generated with NSwag then the enums are referenced with a special property (x-schema) and the generated code does not contain any duplicates.

The fundamental problem is the Swagger spec - it does not allow to reference enums in primitive parameters... and im not even sure if this has been fixed in OpenAPI 3.

Klingensmith answered 19/9, 2017 at 14:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.