Thursday, June 8, 2017

The easy way to enable xDB tracking for Sitecore.Services.Client and Web API

There are several posts on the web that talk about the fact that Sitecore.Services.Client (SSC) and Web API don't allow xDB tracking due to the fact that they are session-less by default.

In this older post, Pavel explains the reason for this, and a provides a solution to make SSC or Web API session aware:

In my post, I will demonstrate how to do this in 5 lines of code.

FXM Is Your Huckleberry

As described by the article, the key is to give the target route a session aware handler right after the SSC route (or Web API route) has been registered in the initialize pipeline.

FXM has a BeaconSessionRouteHandler already built in, because its SSC controllers track activity in xDB from external sites using the magical Beacon script.

So, using what FXM already gives you, all you need is the following "Session State Enabler" Processor in the initialize pipeline, right after the ServicesWebApiInitializer processor.


 using System.Web.Routing;  
 using Sitecore.FXM.Service.Handler;  
 using Sitecore.Pipelines;  
 namespace MyProject.Pipelines.Initialize  
   public class EnableEntityServiceSessionStateProcessor  
     public void Process(PipelineArgs args)  
       var route = RouteTable.Routes["EntityService"] as Route;  
       if (route != null)  
         route.RouteHandler = new BeaconSessionRouteHandler();  


 <configuration xmlns:patch="">  
     <processor type="MyProject.Pipelines.Initialize.EnableEntityServiceSessionStateProcessor, MyProject"  
     patch:after="processor[@type='Sitecore.Services.Infrastructure.Sitecore.Pipelines.ServicesWebApiInitializer, Sitecore.Services.Infrastructure.Sitecore']" />  

 That's it! You can now perform xDB tracking in your SSC or Web API controllers.