Created
June 5, 2013 08:19
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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