Skip to content

Instantly share code, notes, and snippets.

@shizik
Created June 5, 2013 08:23
Show Gist options
  • Save shizik/5712417 to your computer and use it in GitHub Desktop.
Save shizik/5712417 to your computer and use it in GitHub Desktop.
Adds custom JSON formatting rules to controllers of the specified area.
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Http.Routing;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace DemoApplication.Extensions.WebApi
{
public class AreaSpecificCamelCaseJsonFormatter : JsonMediaTypeFormatter
{
private IHttpRouteData _route;
private readonly string _area;
public AreaSpecificCamelCaseJsonFormatter(string area)
{
_area = area;
}
public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
{
_route = request.GetRouteData();
return base.GetPerRequestFormatterInstance(type, request, mediaType);
}
public override Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, HttpContent content, TransportContext transportContext)
{
if (_route.Route.RouteTemplate.StartsWith(_area, StringComparison.InvariantCultureIgnoreCase))
{
// Set the SerializerSettings for the specific area
this.SerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
}
return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment