.NET: Declare an API return type of enumerated strings

Viewed 33

C# allows declaration of enums:

namespace examlimiter.Models
{
    public enum OperationStatus : ushort
    {
        Pending = 0,
        InProgress = 1,
        Success = 2,
        Error = 3,
        Warning = 4
    }
}

However it does not allow the declaration of string enums, which is a problem when working with Swagger/Swashbuckle.

If I define this route in a .NET controller:

[Route("api/testonly")]
[HttpGet]
public OperationStatus GetOperationStatus()
  {
    return OperationStatus.InProgress;
  }

And generate an API based on it with Swashbuckle, this is the result:

{
  "responses": {
    "200": {
      "description": "Success",
      "content": {
        "text/plain": {
          "schema": {
            "$ref": "#/components/schemas/OperationStatus"
          }
        }
      }
    }
  }
}

...

{
  "OperationStatus": {
    "enum": [
      0,
      1,
      2,
      3,
      4
    ],
    "type": "integer",
    "format": "int32"
  }
}

This return type is not very meaningful to a consumer of the API.

I hoped that if I configured the backend to instead return a string, I could use a data annotation to generate something more like this:

{
  "OperationStatus": {
    "enum": [
      "Pending",
      "InProgress",
      "Success",
      "Error",
      "Warning"
    ],
    "type": "string"
  }
}

Is it viable to do this with modern Swagger and .NET?

0 Answers
Related