giovedì 29 gennaio 2015

Asp.Net WebApi 2 and Enum

By default, Web API serializes ENUM data types to the numeric value but humans don't like code, we prefer string description.

So we need to add a Media Type Formatter. In Web API, the media type determines how to serialize the data with a built-in support for JSON, XML and form-urlencoded.

 The following helper method handles the configuration of the media formatter setting. This code should be added in the global.asax.cs file.

using Newtonsoft.Json;

protected void Application_Start()

void SerializeSettings(HttpConfiguration config)
   JsonSerializerSettings jsonSetting = new JsonSerializerSettings();
   jsonSetting.Converters.Add(new Converters.StringEnumConverter());
   config.Formatters.JsonFormatter.SerializerSettings = jsonSetting;

Nessun commento: