How to fix: enum-types for C# Autorest Clients

While creating another post I stubled across the problem that the C# autorest client never created enumerations. All I got was strings with some documentation! Despite specifying the enum-types flag and everything working for Typescript!

After some googeling I found the answer: The enumeration needs the x-ms-enum extension added in the swagger.json. This means that the service generating the swagger.json needs to be updated.

enum-types for C#
x-ms-enum extension in swagger.json

Add Schema Filter

Pre-Requisite: Generate enums as strings, see my post about how to Fix Autorest Problems.

To add the x-ms-enum extension with Swashbuckle, a schema filter needs to be added. The easiest option is the SchemaFilter sample in their documentation:

// Source: Swashbuckle documentation
public class AutoRestSchemaFilter : ISchemaFilter
{
  public void Apply(OpenApiSchema schema, SchemaFilterContext context)
  {
    var type = context.Type;
    if (type.IsEnum)
    {
      schema.Extensions.Add(
        "x-ms-enum",
        new OpenApiObject
        {
          ["name"] = new OpenApiString(type.Name),
          ["modelAsString"] = new OpenApiBoolean(true)
        }
      );
    };
  }
}

The schema filter is added to the AddSwaggerGen functionality in the Startup.cs:

services.AddSwaggerGen(c =>
{
[...]
    c.SchemaFilter<AutoRestSchemaFilter>();
}

The autorest generator for C# ignores the flag enum-types.

You can see all code changes in a sample project: https://github.com/AngelaE/blog-integration-test/pull/1

Caveat

Before adding the annotations it is worth checking whether it really is a good idea to ‘force’ C# clients to generate enumerations as types. In the following cases it could be better to use strings:

  1. Enum values change regularly
  2. The same enum is used in multiple places and a different type is generated each time.

It would be a good idea to generate the client(s) and check how they look like.

Update 28th May 2021:

There is a new modeler in the alpha phase which seems better at generating enumerations without adding any custom extensions. Running autorest without fixing the extensions will automatically pick the new modelerfour. When I ever have some time I am going to have a play with it…

Angela Evans

Senior Software Engineer at Diligent in Christchurch, New Zealand