Is it possible to add x-enum-varnames to all enums in NSwag? I have this example but then you have to specify all the enums. Is there a more generic solution? Also, this example creates a second instance ResultCode2 which I don't understand.
https://github.com/RicoSuter/NSwag/issues/1993
public class NSwagProcessor : IOperationProcessor
{
public bool Process( OperationProcessorContext context )
{
JsonSchema schema = JsonSchema.FromType<ResultCode>();
if( schema.ExtensionData == null )
{
schema.ExtensionData = new Dictionary<string, object>();
}
string[] enumerationNames = new string[ schema.EnumerationNames.Count ];
schema.EnumerationNames.CopyTo( enumerationNames, 0 );
schema.ExtensionData.Add( "x-enum-varnames", enumerationNames );
if( context.Settings.TypeMappers.Any( t => t.MappedType == typeof( ResultCode ) ) == false )
{
context.Settings.TypeMappers.Add( new ObjectTypeMapper( typeof( ResultCode ), schema ) );
}
return true;
}
}
...
services.AddOpenApiDocument( config => {
config.OperationProcessors.Add( new NSwagProcessor() );
} );
This creates:
"ResultCode": {
"type": "integer",
"description": "",
"x-enumNames": [
"Error",
"Success"
],
"enum": [
0,
1
]
},
...
"ResultCode2": {
"title": "ResultCode",
"type": "integer",
"description": "",
"x-enumNames": [
"Error",
"Success"
],
"enum": [
0,
1
],
"x-enum-varnames": [
"Error",
"Success"
]
},
I found another solution, you can add a Schema processor to the NSwag openapi generation. By adding the following schema processor:
public class XEnumVarnamesNswagSchemaProcessor : ISchemaProcessor
{
public void Process(SchemaProcessorContext context)
{
if (context.Type.IsEnum)
{
if (context.Schema.ExtensionData is not null)
{
context.Schema.ExtensionData.Add("x-enum-varnames", context.Schema.EnumerationNames.ToArray());
}
else
{
context.Schema.ExtensionData = new Dictionary<string, object>()
{
{"x-enum-varnames", context.Schema.EnumerationNames.ToArray()}
};
}
}
}
}
An extra field will be added to all openapi enum schemas/types. You need to add the processor to the NSwag service in Startup.cs.
services.AddOpenApiDocument(configuration =>
{
configuration.SchemaProcessors.Add(new XEnumVarnamesNswagSchemaProcessor());
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With