Monday, June 29, 2015

Using SignalR with Sitecore

If you are unfamiliar with SignalR and need to set it up I will be posting an intro to SignalR on my other blog (Programming Medeley) in a few days.  Otherwise reading this post I will assume that you have a basic understanding of what SignalR is and how it works.
When developing in Sitecore with SignalR there is one major issue that you will run into (aside from basic routing).  That issue is the fact that you do not have a Sitecore site context within your SignalR context.  This causes issues with getting item URLs or using the Glass Mapper.

Missing Site Context

The fix for this is actually quite simple though.  You simply need to set the Sitecore site context on every request. 
To get the SiteContext you simply call Sitecore.Sites.SiteContextFactory.GetSiteContext and pass in the hostname (which can be found within the context of the Hub as this.Context.Request.Url.Host) and an empty path and it will give you a SiteContext. 
Once we have this all we have to do is set the current site to this context by setting Sitecore.Context.Site to this SiteContext. 
I use the single line:
Sitecore.Context.Site = Sitecore.Context.Site ?? SitecontextFactory.GetSiteContext(this.Context.Request.Url.Host, “/”);

Routing

As for the routing issue that you may run into, this is the same as setting up WebApi.  You need to ensure the route is registered in the Application_Start of the Global.asax. 

The command for this is (using the Global Configuration):
GlobalConfiguration.Configuration.Routes.MapHttpRoute(“signalrHub”, “
signalr/{controller}”);          

No comments:

Post a Comment