Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 -

public class LoginResponse
{
    public LoginResult LoginResult { get; set; }
}

public enum LoginResult
{
    AwaitingEmailConfirmation = 0,
    Locked = 1,
    Failed = 2,
    Success = 3
}

Which generates the Swagger JSON of -

"definitions":{  
"LoginResponse":{  
   "type":"object",
   "additionalProperties":false,
   "required":[  
      "loginResult"
   ],
   "properties":{  
      "loginResult":{  
         "$ref":"#/definitions/LoginResult"
      }
   }
},
"LoginResult":{  
   "type":"integer",
   "description":"",
   "x-enumNames":[  
      "AwaitingEmailConfirmation",
      "Locked",
      "Failed",
      "Success"
   ],
   "enum":[  
      0,
      1,
      2,
      3
   ]
},

and when running swagger codegen on the JSON I get the following LoginResult model in my IO.Swagger project for C# (targetFramework 5.0 chosen) -

[JsonConverter(typeof(StringEnumConverter))]

public enum LoginResult
{

    /// <summary>
    /// Enum _0 for value: 0
    /// </summary>
    [EnumMember(Value = "0")]
    _0 = 1,

    /// <summary>
    /// Enum _1 for value: 1
    /// </summary>
    [EnumMember(Value = "1")]
    _1 = 2,

    /// <summary>
    /// Enum _2 for value: 2
    /// </summary>
    [EnumMember(Value = "2")]
    _2 = 3,

    /// <summary>
    /// Enum _3 for value: 3
    /// </summary>
    [EnumMember(Value = "3")]
    _3 = 4
  }

}

Could someone help describe how I get the enums to generate with the same names etc as the original LoginResult Model in the IO.Swagger generated client code using swagger-codegen?

like image 565
WickedW Avatar asked Oct 04 '18 14:10

WickedW


2 Answers

Using Nswag 13.10.7 and .netcore 3.1

Edit your Startup.ConfigureServices to something like

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers()
                .AddJsonOptions(options =>
                {
                    options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                });
             ...
         }
like image 80
Perbert Avatar answered Oct 19 '22 01:10

Perbert


You can use this code in your start up:

services.AddMvc(option => option.EnableEndpointRouting = false).AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
        });
like image 4
Jafar ashrafi Avatar answered Oct 19 '22 02:10

Jafar ashrafi