✅ Enums as strings on AspNetCore controller .NET 9
I have added this enum
In swagger it shows as expected
In swagger it shows as expected



[HttpPost("/authorize", Name = "Authorize")]
[Consumes("application/x-www-form-urlencoded")]
[ProducesResponseType<AuthorizeResponse>(StatusCodes.Status200OK)]
public async Task<IActionResult> Authorize(
[FromForm] string login,
[FromForm] string password,
[FromForm] Locale? locale,
CancellationToken cancellationToken)[TypeConverter(typeof(StringEnumConverter<Locale>))]
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum Locale
{
[JsonStringEnumMemberName("ar_AE")]
ArabicUae,
}public class StringEnumConverter<T> : TypeConverter where T : struct, Enum
{
public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value)
{
if (value is string stringValue)
{
var type = typeof(T);
foreach (var field in type.GetFields())
{
var attr = field.GetCustomAttribute<JsonStringEnumMemberNameAttribute>();
if (attr != null && string.Equals(attr.Name, stringValue, StringComparison.OrdinalIgnoreCase))
{
return (T)Enum.Parse(type, field.Name);
}
}
if (Enum.TryParse<T>(stringValue, true, out var result))
{
return result;
}
}
throw new ArgumentException($"Cannot convert {value} to {typeof(T).Name}");
}
}