Skip to content

Instantly share code, notes, and snippets.

@shizik
Created June 5, 2013 08:19
Show Gist options
  • Save shizik/5712399 to your computer and use it in GitHub Desktop.
Save shizik/5712399 to your computer and use it in GitHub Desktop.
Attribute can be used on specific action or controller to override the default JSON formatting for WebApi.
using System;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http.Controllers;
using Newtonsoft.Json.Serialization;
namespace DemoApplication.Extensions.WebApi
{
public class CamelCaseJsonAttribute : Attribute, IControllerConfiguration
{
public void Initialize(HttpControllerSettings config,
HttpControllerDescriptor controllerDescriptor)
{
var formatter = config.Formatters.OfType<JsonMediaTypeFormatter>().SingleOrDefault();
if (formatter == null) return;
config.Formatters.Remove(formatter);
// We need to new this, so it doesn't overwrite global settings
formatter = new JsonMediaTypeFormatter
{
SerializerSettings = { ContractResolver = new CamelCasePropertyNamesContractResolver() }
};
config.Formatters.Insert(0, formatter);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment