I have come across a piece of code in my Web API project, which has a class of this structure:
public class QuestionDto
{
public bool disabled {get;set;}
public int id {get;set;}
public int order {get;set;}
public PositionDto pagePosition {get;set;}
public string title {get;set;}
}
public enum PositionDto
{
FullWidth = 0,
Half = 1
}
There is an API call that returns QuestionDto
, along the lines of:
[Route("")]
[HttpGet]
[ResponseType(typeof(QuestionDto))]
public async Task<IHttpActionResult> GetCategoryQuestions()
{
return Ok(new QuestionDto { PagePosition = PagePositionDto.Half });
}
Here is a snip from the Chrome console network tab showing the repsonse for this API call:
How can the enum be returning its text value, rather than its int value?
To confuse this even further, if I then take this same class structure and copy and paste to a differrent project, the api call returning this object will return the int value - which is what I would expect.
So ho can the fist project be returning the string value?
Is there some setting somewhere which can make this enum return its string value?
name() method of Enum returns the exact same String which is used to declare a particular Enum instance like in WeekDays Enum if we have MONDAY as one Enum instance then the name() will return String "MONDAY".
The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.
No they cannot. They are limited to numeric values of the underlying enum type.
To get all values of an enum, we can use the Enum. GetValues static method. The Enum. GetValues method returns an array of all enum values.
There is a setting that can be added to a variable, that will return the string value in JSON.
It can either be set on the variable declaration like this:
[JsonConverter(typeof(StringEnumConverter))]
public PositionDto pagePosition { get; set; }
or it can be set globally, like this:
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.Converters.Add(new StringEnumConverter());
if you are using asp.net core use JsonStringEnumConverter instead of StringEnumConverter
[JsonConverter(typeof(JsonStringEnumConverter))]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With