Chris Adams
Chris Adams

Reputation: 1018

Get the item matching a URL in 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?

Upvotes: 6

Views: 12071

Answers (4)

Michael
Michael

Reputation: 353

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.

Upvotes: 5

Chris Adams
Chris Adams

Reputation: 1018

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);

Upvotes: 8

Martijn van der Put
Martijn van der Put

Reputation: 4092

You can use the method ItemManager.GetItem(itemPath, language, version, database, securityCheck) To resolve an item based on it's (full)path.

Upvotes: 0

Ruud van Falier
Ruud van Falier

Reputation: 8877

Don't really get what you're trying to do (with your AJAX request and such), but if you want http://www.mysite.com/abc/def to resolve the item sitecore/content/MySite/Home/abc/def, you need to configure your <site> in the web.config like this:

<site name="MySite" hostName="www.mysite.com" rootPath="/sitecore/content/MySite" startItem="/Home" *other attributes here* />

Upvotes: 0

Related Questions