RobVious RobVious - 1 year ago 192
C# Question

Serializing Multiple Enum Values in WebApi

If I have an Enum like this:

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;

.ContractResolver = new CamelCasePropertyNamesContractResolver();

Answer Source

I'm an idiot.


Is all that was needed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download