Forum Discussion

Kiran Kakanur's avatar
Kiran Kakanur
Copper Contributor
Mar 05, 2018
Solved

How to get Friendly URL of a Publishing page using CSOM

Environment: SharePoint 2013 on-premise   I need to retrieve the friendly URL of a Publishing page.   I tried checking the "Hide physical URLs from search" box in the page properties, but thi...
  • paulpascha's avatar
    Mar 06, 2018

    Unfortunately GetFriendlyUrlsForListItem() is not available in CSOM. I quickly wrote a sample program for you to show how you could retrieve the Friendly URL's for one of your Publishing Pages. See code below. Hope this gives you enough inspiration to write your own Production-ready code.

     

    Note that this code makes use of AuthenticationManager and Extensions method(s) that are part of SharePointPnPCore* NuGet package. You could perfectly do without it...

     

    class Program
        {
            static void Main(string[] args)
            {
                const string siteUrl = "";
                const string userName = "";
                const string password = "";
    
                using (var ctx = new AuthenticationManager().GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
                {
                    var navigationTermSet = TaxonomyNavigation.GetTermSetForWeb(ctx, ctx.Web, "GlobalNavigationTaxonomyProvider", true);
                    var allNavigationTerms = navigationTermSet.GetAllTerms();
    
                    ctx.Load(allNavigationTerms, t => t.Include(
                        i => i.TargetUrl, 
                        i => i.LinkType, 
                        i => i.TaxonomyName,
                        i => i.Parent));
    
                    ctx.ExecuteQuery();
    
                    var navigationTermsForPage = allNavigationTerms.Where(
                        t => t.LinkType == NavigationLinkType.FriendlyUrl && 
                        t.TargetUrl.Value.Contains("/Pages/mypublishingpage.aspx")); // insert your publishing page URL here
    
                    ctx.Web.EnsureProperty(w => w.Url); 
    
                    foreach (var navTerm in navigationTermsForPage)
                    {
                        var url = "";
    
                        ctx.Load(navTerm);
    
                        url = InsertUrlRecursive(navTerm, url);
    
                        Console.WriteLine($"{ctx.Web.Url}{url}");
                    }
                }            
            }
    
            private static string InsertUrlRecursive(NavigationTerm navTerm, string url)
            {
                url = url.Insert(0, $"/{navTerm.TaxonomyName}");
    
                if (!navTerm.Parent.ServerObjectIsNull())
                {
                    url = InsertUrlRecursive(navTerm.Parent, url);
                }
    
                return url;
            }
        }

     

Resources