在我正在构建的站点中,我正在尝试使用引用来验证AJAX请求来自正确的URL。
为此,我想让Sitecore解析项目的URL。例如,
http://www.mysite.com/abc/def
可能会解析到路径上的项目
sitecore/Content/MySite/Home/abc/def
在我的代码中推荐的方法是什么?
感谢所有的答案,但他们都没有做我需要的一切。这对我有用。
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);
不要真正得到你想要做的事情(使用你的AJAX请求等),但是如果你想让http://www.mysite.com/abc/def
解析项目sitecore/content/MySite/Home/abc/def
,你需要在web.config中配置你的<site>
,如下所示:
<site name="MySite" hostName="www.mysite.com" rootPath="/sitecore/content/MySite" startItem="/Home" *other attributes here* />
您可以使用ItemManager.GetItem(itemPath, language, version, database, securityCheck)
方法根据它的(完整)路径解析项目。
这个答案更适合其他访问这个问题的访客。如果是Sitecore 8,您可以这样做:
new Sitecore.Data.ItemResolvers.ContentItemPathResolver().ResolveItem(<string path>)
其中<string path>
就像任何本地路径(或相关网址,如果你愿意的话),sitecore可以为你生成的字符串。当使用displayname值而不是项目名称时(如果你有一个多语言站点可能就是这种情况),这对于从数据库中实际检索相应的Item
非常方便。
在我的例子中,我用它来显示一个有效的痕迹,其中父路径DO添加了上下文语言项目版本,但请求的页面没有要渲染的上下文语言版本。 Sitecore.Context.Database.GetItem(<string path>)
无法解析基于显示名称的路径,而ResolveItem方法确实...在一天中搜索了一个关于这种情况的好答案。
现在质疑自己,为什么这个用不多......?对于拥有大树的网站来说,这可能是一个昂贵的查询。这是你自己要考虑的事情。