I’m trying to improve my Swagger UI for Web API documentation. Right now, all my enums show up as numbers, but I’d like them to appear as text. This would make it easier to perform POST actions without having to check the enum values every time.
I attempted to use DescribeAllEnumsAsStrings
, but that resulted in the server receiving strings rather than enum values, which is not the desired outcome.
Does anyone have a viable solution for this? I’m hoping to configure Swagger UI so that it displays enum texts while still sending the proper enum values to the server.
Below is a simplified example of my current setup:
public enum ImportanceLevel
{
Low,
Normal,
Urgent
}
public class Message
{
public string Text { get; set; }
public ImportanceLevel Importance { get; set; }
}
[HttpPost]
public IActionResult SendMessage(Message message)
{
// Handle sending the message
}
In the Swagger UI documentation, I want the Importance field to show ‘Low’, ‘Normal’, and ‘Urgent’, rather than 0, 1, or 2. Any suggestions?
hey Emma, I ran into this issue too! try using the [EnumMember] attribute from System.Runtime.Serialization. it lets u specify the string representation for each enum value. like this:
[EnumMember(Value = “Low”)]
Low = 0,
hope that helps! lmk if u need more info 
One approach you might consider is using the SwaggerEnumDescriptor attribute from Swashbuckle.AspNetCore.Annotations. This allows you to provide custom descriptions for your enum values without altering the underlying enum implementation.
Here’s how you could apply it:
[SwaggerSchema(Description = "Importance level of the message")]
public enum ImportanceLevel
{
[SwaggerEnumDescriptor("Low priority")]
Low,
[SwaggerEnumDescriptor("Normal priority")]
Normal,
[SwaggerEnumDescriptor("Urgent priority")]
Urgent
}
This method maintains the correct enum values on the server side while providing more descriptive text in the Swagger UI. Remember to enable the SwaggerAnnotations in your Startup.cs file for this to work.
I’ve dealt with this issue before, and I found that using the JsonConverter attribute can be quite effective. You can create a custom JsonConverter that handles the serialization and deserialization of your enum. Here’s a basic example:
public class StringEnumConverter : JsonConverter<ImportanceLevel>
{
public override ImportanceLevel Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return Enum.Parse<ImportanceLevel>(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, ImportanceLevel value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString());
}
}
Then apply it to your enum:
[JsonConverter(typeof(StringEnumConverter))]
public enum ImportanceLevel
{
Low,
Normal,
Urgent
}
This approach allows Swagger UI to display the enum values as strings while still maintaining the correct enum type on the server side. It’s a bit more work upfront, but it gives you full control over the serialization process.