By default when you return an enum value as part of your data contract in ASP.NET Core, it will be serialized as a number value.
Here is an example of our data contract:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class WeatherForecast | |
{ | |
public DateTime Date { get; set; } | |
public int TemperatureC { get; set; } | |
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); | |
public string? Summary { get; set; } | |
public WeatherType WeatherType { get; set; } | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public enum WeatherType | |
{ | |
Sunny=0, | |
Rainy=1 | |
} |
And how it will be returned by our API:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"date": "2022-09-25T10:52:14.8018192+02:00", | |
"temperatureC": -8, | |
"temperatureF": 18, | |
"summary": "Scorching", | |
"weatherType": 1 | |
} |
But what if we want to return the enum value as a string instead of a number?
We can achieve this by updating our JsonOptions and register the JsonStringEnumConverter
:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
builder.Services.AddControllers() | |
.AddJsonOptions(opts => | |
{ | |
var enumConverter = new JsonStringEnumConverter(); | |
opts.JsonSerializerOptions.Converters.Add(enumConverter); | |
}); |
If we now call our API, the result looks like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"date": "2022-09-25T10:52:14.8018192+02:00", | |
"temperatureC": -8, | |
"temperatureF": 18, | |
"summary": "Scorching", | |
"weatherType": "Rainy" | |
} |