Mike Robbins

Sitecore Developer Blog

Follow me on GitHub

Web API Sitecore ID Formatter

When using Web API, Sitecore ID's serialise with {} around the IDs. This can cause issues when working with JSON as this denotes objects encapsulation.

JSON Sitecore ID's

JSON Sitecore ID's

Below is a custom formatter to format Sitecore item IDs without the {}. This example has Web API registered to run alongside Web Item API.

See Patrick Delancy's blog post about running Web API alongside Web Item API http://patrickdelancy.com/2013/08/sitecore-webapi-living-harmony/

The corresponding JSON

The corresponding JSON

public class RegisterWebApiRoute
{
  public void Process(PipelineArgs args)
  {
    var config = GlobalConfiguration.Configuration;
    config.Routes.MapHttpRoute("DefaultApiRoute",
    "mikerobbinsapi/{controller}/{id}",
    new { id = RouteParameter.Optional });
     
    var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
    config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
    config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new IDConverter());
  }
}
public class IDConverter : JsonConverter
{
  public override bool CanConvert(Type objectType)
  {
    return objectType == typeof(ID);
  }
  
  public override bool CanRead
  {
    get
    {
      return false;
    }
  }

  public override bool CanWrite
  {
    get
    {
      return true;
    }
  }

  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  {
    var id = (ID)value;
    writer.WriteValue(id.ToString().Replace("{", "").Replace("}", "").ToUpperInvariant());
  }

  public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  {
    // Default reader used
    throw new NotImplementedException();
  }
}