获取与Sitecore中的URL匹配的项目

Chr*_*ams 5 sitecore

在我正在构建的站点中,我正在尝试使用引用来验证AJAX请求来自正确的URL.

为此,我想让Sitecore解析项目的URL.例如,

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

可能会解析到路径上的项目

sitecore/Content/MySite/Home/abc/def

在我的代码中推荐的方法是什么?

Chr*_*ams 6

感谢所有的答案,但他们都没有做我需要的一切.这对我有用.

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);
Run Code Online (Sandbox Code Playgroud)

  • 在多语言系统的情况下,这可能无法很好地工作。?? (2认同)

Mic*_*ael 5

这个答案更适合其他访问者提出这个问题。对于 Sitecore 8,您可以执行以下操作:

new Sitecore.Data.ItemResolvers.ContentItemPathResolver().ResolveItem(<string path>)
Run Code Online (Sandbox Code Playgroud)

其中<string path>类似于 sitecore 能够为您生成的任何本地路径(或相对 url,如果您愿意的话)字符串。当使用显示名称值而不是项目名称时(如果您有多语言站点,可能会出现这种情况),这对于Item从数据库中实际检索相应的内容非常方便。

在我的例子中,我使用它来显示有效的面包屑,其中父路径确实添加了上下文语言项版本,但请求的页面没有要呈现的上下文语言版本。Sitecore.Context.Database.GetItem(<string path>)无法解析基于显示名称的路径,而 ResolveItem 方法却可以...在这种情况下搜索了一天以找到一个好的答案。

现在问自己,为什么这个很少被使用......?对于拥有一棵大树的站点来说,这可能是一个昂贵的查询。这是你自己要考虑的事情。


Ruu*_*ier 0

不太明白你想要做什么(使用 AJAX 请求等),但如果你想http://www.mysite.com/abc/def解析 item sitecore/content/MySite/Home/abc/def,你需要<site>在 web.config 中进行如下配置:

<site name="MySite" hostName="www.mysite.com" rootPath="/sitecore/content/MySite" startItem="/Home" *other attributes here* />
Run Code Online (Sandbox Code Playgroud)