Last active
September 20, 2023 18:22
-
-
Save keyan1603/888393a52f512267e78c72289154653b to your computer and use it in GitHub Desktop.
Get Sitecore Context item for a page during AJAX calls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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