question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

nswag c# code gen: how to generate enum properties as string

See original GitHub issue

I have a service that exposes a swagger.json file that goes like this:

 ...
      "AccountSummary": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "serviceStatus": {
            "description": "The user service status. See the enumerated type for all the details.",
            "oneOf": [
              {
                "$ref": "#/components/schemas/ServiceStatus"
              }
            ]
          },
          "accountingStatus": {
            "description": "The user account status. See the enumerated type for all the details.",
            "oneOf": [
              {
                "$ref": "#/components/schemas/AccountStatus"
              }
            ]
          }
        }
      },
...
      "AccountStatus": {
        "type": "string",
        "description": "",
        "x-enumNames": [
          "Good",
          "PoorStanding",
          "Collection"
        ],
        "enum": [
          "Good",
          "PoorStanding",
          "Collection"
        ]
      },

When I use nswag to generate a client to contact this API, it generates code like this for the DTO:

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.3.4.0 (Newtonsoft.Json v12.0.0.0)")]
public partial class AccountSummary 
{
	/// <summary>The user service status. See the enumerated type for all the details.</summary>
	[Newtonsoft.Json.JsonProperty("serviceStatus", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
	[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
	public ServiceStatus ServiceStatus { get; set; }

	/// <summary>The user account status. See the enumerated type for all the details.</summary>
	[Newtonsoft.Json.JsonProperty("accountingStatus", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
	[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
	public AccountStatus AccountingStatus { get; set; }
}

So, as you can see, the DTO uses an enum for ServiceStatus and AccountingStatus.

We’ve been using nswag like this for a few years and been mostly satisified. But one problem that we found is that when the service adds a new value for the enum, it has the potential of breaking all the clients. For example, if the service adds a value Deleted the the AccountStatus enum, all the cliens will start to break with an error that says something like Deleted is not a recognized value for AccountStatus.

To fix this issue, we would want to tell nswag to generate a simple string (and not an enum) when it sees an enum in a swagger.json spec. Could you please tell me how to do it? I looked in the nswag documentation but I couldn’t find how to do it.

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:1
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
jkone27commented, Oct 4, 2022

This would still be useful as an option, many time wrong enum description in server side can cause problems to client, wheras working with simple strings would fix it. for most clients this would be acceptable, as changes in enum values dont need change in contract when type is just a string. We are also facing similar issues e.g. with apis generated in java or openapi contracts specified manually…

1reaction
RicoSutercommented, Feb 22, 2021

Currently there is no such option, you have to postprocess the file before generating the clients - this is quite simple with NJS’s schema visitor class, just remove all “enum” properties…

Something I’d like to add anyway is some sort of “resilient” enum converter, e.g. if the value does not exist then the serializer falls back to eg “Unknown” - this way you lose information but at least deserialization does not fail.

Another option is to use string-based/custom enums instead of “real” enums.

Read more comments on GitHub >

github_iconTop Results From Across the Web

C# NSwag and swagger-codegen with Enums
I have a .Net Core v2.1 Web API which uses NSwag to generate its Swagger Json. I have a response model as such...
Read more >
Generating client code with NSwag for Enumeration class
This post describes how we can render an Enumeration class as an Enum type in client code with NSwag by implementing Swagger ISchemaFilter....
Read more >
Using OpenApiReference To Generate Open API Client ...
I this post I show how you can customise the code generated by the OpenApiReference tooling from Visual Studio's Connected Services using ...
Read more >
C# NSwag and swagger-codegen with Enums
I have a .Net Core v2.1 Web API which uses NSwag to generate its Swagger Json. I have a response model as such...
Read more >
C# Enum generation - underlying int values do not
The generated enum in the c sharp api client (using NSwag Studio for windows v 13.2.3.0) looks like this - the underlying integer...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found