Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the item matching a URL in Sitecore

Tags:

sitecore

In a site I'm building, I'm trying to use the referer to verify AJAX requests are coming from the correct URLs.

To do this I'd like to get Sitecore to resolve a URL to an Item. For example,

http://www.mysite.com/abc/def

might resolve to the item at the path

sitecore/Content/MySite/Home/abc/def

What's the recommended way to go about this in my code?

like image 371
Chris Adams Avatar asked Dec 11 '12 06:12

Chris Adams


2 Answers

Thanks for all the answers but none of them did everything I needed. This worked for me.

var url = new Uri(...);

// Obtain a SiteContext for the host and virtual path
var siteContext = SiteContextFactory.GetSiteContext(url.Host, url.PathAndQuery);

// Get the path to the Home item
var homePath = siteContext.StartPath;
if (!homePath.EndsWith("/"))
    homePath += "/";

// Get the path to the item, removing virtual path if any
var itemPath = MainUtil.DecodeName(url.AbsolutePath);
if (itemPath.StartsWith(siteContext.VirtualFolder))
    itemPath = itemPath.Remove(0,siteContext.VirtualFolder.Length);

// Obtain the item
var fullPath = homePath + itemPath;
var item = siteContext.Database.GetItem(fullPath);
like image 84
Chris Adams Avatar answered Sep 22 '22 03:09

Chris Adams


This answer is more for other visitors hitting this SO question. In case of Sitecore 8 you could do this:

new Sitecore.Data.ItemResolvers.ContentItemPathResolver().ResolveItem(<string path>)

Where <string path> is like any local path (or relative url, if you will) string that sitecore would be able to generate for you. When using displayname values instead of item names (possibly the case if you have a multilingual site), this is very handy to actually retrieve the corresponding Item from database.

In my case I use this to show a valid breadcrumb where the parent paths DO have the context language item version added, but the requested page has no context language version to render. Sitecore.Context.Database.GetItem(<string path>) couldn't resolve the displayname-based path, while the ResolveItem method does... searched a day for a good answer on this case.

Questioning myself now, why this isn't used much...? Maybe it is an expensive query for a site with a big tree. That is something to consider yourself.

like image 34
Michael Avatar answered Sep 20 '22 03:09

Michael