3

If I have an Enum like this:

[Flags]
public enum EyeColor {
    All = 1,
    Brown = 2,
    Blue = 4,
    Hazel = 8,
    Green = 16
}

And then return a JSON result like this:

jsonBody.EyeColor = EyeColor.Brown | EyeColor.Blue;

I see the following in my jsonBody on the client:

"Brown, Blue"

However if I send the above string to WebAPI via an EyeColor property:

var eyeColor = "Brown, Blue"
var query = '?Index=1&EyeColor=` + eyeColor;
// send json GET request and use [FromUri] to extract

Serverside, I get:

dto.EyeColor: 0

Though if I do this:

var eyeColor = "All"
var query = '?Index=1&EyeColor=` + eyeColor;
// send json GET request and use [FromUri] to extract

I get

dto.EyeColor: All

So what I'm wondering is - in the event where I want to not only retrieve a string-serialized Enum from WebApi, but also send a string to represent multiple Enums that have been selected (and deserialized into multiple enums), what do I need to do?

My Global.asax:

        JsonSerializerSettings jSettings = new JsonSerializerSettings();
        jSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
           GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = jSettings;

      GlobalConfiguration.Configuration
      .Formatters
      .JsonFormatter
      .SerializerSettings
      .ContractResolver = new CamelCasePropertyNamesContractResolver();

1 Answer 1

4

I'm an idiot.

"Brown,+Blue"

Is all that was needed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.