Skip to content

Instantly share code, notes, and snippets.

@komainu85
Last active June 29, 2016 09:49
Show Gist options
  • Save komainu85/a9fc2a103b967181364e to your computer and use it in GitHub Desktop.
Save komainu85/a9fc2a103b967181364e to your computer and use it in GitHub Desktop.
Web API Registration Sitecore
public class RegisterWebApiRoute
{
public void Process(PipelineArgs args)
{
var config = GlobalConfiguration.Configuration;
config.Routes.MapHttpRoute("DefaultApiRoute",
"MikeAPI/{controller}/{action}/{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 AbortSitecoreForKnownRoutes : HttpRequestProcessor
{
public override void Process(HttpRequestArgs args)
{
var routeCollection = RouteTable.Routes;
var routeData = routeCollection.GetRouteData(new HttpContextWrapper(args.Context));
if (routeData == null || args.Url.ItemPath.Contains("api/sitecore")) return;
HttpContext.Current.RemapHandler(routeData.RouteHandler.GetHttpHandler(HttpContext.Current.Request.RequestContext));
args.AbortPipeline();
}
}
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)
{
// the default deserialization works fine,
// but otherwise we'd handle that here
throw new NotImplementedException();
}
}
<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<httpRequestBegin>
<processor
patch:after="processor[@type='Sitecore.Pipelines.HttpRequest.CustomHandlers, Sitecore.Kernel']"
type="MikeRobbins.web.WebApi.AbortSitecoreForKnownRoutes, MikeRobbins.web"/>
</httpRequestBegin>
<initialize>
<processor type="MikeRobbins.web.WebApi.RegisterWebApiRoute, MikeRobbins.web"/>
</initialize>
</pipelines>
</sitecore>
</configuration>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment