Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum returning string value in WebAPI

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:

enter image description here

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?

like image 304
Alex Avatar asked Feb 23 '18 14:02

Alex


People also ask

Does enum return string?

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".

Can enum string value?

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.

Can enums contain strings?

No they cannot. They are limited to numeric values of the underlying enum type.

How do I return all enum values?

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.


2 Answers

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());
like image 152
Alex Avatar answered Oct 19 '22 07:10

Alex


if you are using asp.net core use JsonStringEnumConverter instead of StringEnumConverter [JsonConverter(typeof(JsonStringEnumConverter))]

like image 40
Zubaer Naseem Avatar answered Oct 19 '22 07:10

Zubaer Naseem