31

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 how can the first project be returning the string value?

Is there some setting somewhere which can make this enum return its string value?

0

6 Answers 6

48

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());
Sign up to request clarification or add additional context in comments.

3 Comments

@Alex First line of second code block, var json = config. ...
@LWChris Typically you will need to this line of code in .NET 4.x in your 'WebApiConfig.cs' file within the App_Start folder. This contains a Register method passing in a HttpConfiguration object (config), where you setup stuff like http filters, route configuration, formatters etcetera
In System.Text.Json.Serialization you can use [JsonConverter(typeof(JsonStringEnumConverter))]
25

If you are using asp.net core or dotnet 6, use JsonStringEnumConverter instead of StringEnumConverter [JsonConverter(typeof(JsonStringEnumConverter))]

Comments

18

For WebAPI with .Net 5.0 you can do this in ConfigureServices in Startup.cs for global solution to enums:

services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
    options.JsonSerializerOptions.IgnoreNullValues = true;
});

Comments

12

For .NET Core 6, use the following code in the Program.cs

builder.Services.AddControllers().AddJsonOptions(options =>
{
   options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());

   options.JsonSerializerOptions.DefaultIgnoreCondition =
       JsonIgnoreCondition.WhenWritingNull;
});

1 Comment

This is actually a good way of doing it throughout the whole project, not just endpoint specific. And is a modern approach
2

Alex has the right answer - just to add a little - if you're using Newtonsoft.Json you'll need to include "using Newtonsoft.Json.Converters;" to have StringEnumConverter available.

Comments

-3
return Ok(new QuestionDto { PagePosition.Value = PagePositionDto.Half.Value });

1 Comment

Please elaborate how your code solves the issue.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.