Skip to content

Instantly share code, notes, and snippets.

@keyan1603
Last active September 20, 2023 18:22
Show Gist options
  • Save keyan1603/888393a52f512267e78c72289154653b to your computer and use it in GitHub Desktop.
Save keyan1603/888393a52f512267e78c72289154653b to your computer and use it in GitHub Desktop.
Get Sitecore Context item for a page during AJAX calls
// Get the current URL from the page where the AJAX call has been made
var url = HttpContext.Current.Request.UrlReferrer; // Note the UrlReferrer
// Get the context
var siteContext = SiteContextFactory.GetSiteContext(url.Host, url.PathAndQuery);
if (siteContext?.StartPath == null)
{
throw new Exception(); // log or handle the exception
}
// Get the path of Home item
var homeItemPath = siteContext.StartPath;
if (!homeItemPath .EndsWith("/"))
{
homeItemPath += "/";
}
// Get item path of the page
// Add using Sitecore; reference for MainUtil. It is present in Sitecore.MainUtil
var contextItemPath = MainUtil.DecodeName(url.AbsolutePath);
// Find virtual paths if any and remove the virtual folder from the path
if (contextItemPath.StartsWith(siteContext.VirtualFolder))
{
contextItemPath = contextItemPath.Remove(0, siteContext.VirtualFolder.Length);
}
// Get the item
var fullPath = homeItemPath + contextItemPath;
return siteContext.Database.GetItem(fullPath);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment