How to get full URL from friendly URL
-
02-10-2020 - |
Question
I have a method, that uses SPWeb.GetFile(url)
. When we use Managed Navigation, I have a friendly URL and GetFile(friendlyUrl)
doesn't work:
Value does not fall within the expected range.
How can I get the full Url (like 'http://mysite/Pages/allproducts.aspx') from a friendly URL (like 'http://mysite/products')?
Solution
Try this function
public string GetPageUrl(string friendlyUrl) {
//current web
SPWeb web = SPContext.Current.Web;
//check if the current web is a publishing weg
if (PublishingWeb.IsPublishingWeb(web)) {
//get the pages list id
Guid listId = PublishingWeb.GetPagesListId(web);
//retrieve the pages list
SPList pagesList = web.Lists[listId];
//itterate trough the pages
foreach (SPListItem item in pagesList.Items) {
//retrieve the terms used for the navigation (this can be multiple terms)
IList<NavigationTerm> terms = TaxonomyNavigation.GetFriendlyUrlsForListItem(item, false);
//check if the pages has terms associated with it
if (terms.Count > 0) {
//use the GetResolvedDisplayUrl to retrieve the page friendly urls
if(terms[0].GetResolvedDisplayUrl(string.Empty).ToLower() == friendlyUrl.ToLower())
return item.File.Url;
}
}
}
return friendlyUrl;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange