Sunday, July 7, 2013

How to get friendly URL of the current page in Sharepoint programmatically

Friendly URLs is the new feature of Sharepoint 2013. It allows to show urls like http://example.com/products/ instead of http://example.com/products/pages/default.aspx in browser address bar, which is shorter and more user friendly. For developers it adds several challenges. I wrote about several of them already in the following posts (here, here and here). In web development in general it is often needed to get URL of the current page. When you use structural navigation and regular URLs it is quite easy:

   1: string url = HttpContext.Current.Request.Uri.OriginalString;

But how to get friendly URL of the current page when managed metadata navigation is used? The answer is TaxonomyNavigationContext class. It contains several properties which will help you to work with friendly URLs programmatically, e.g. HasFriendlyUrl and ResolvedDisplayUrl (all properties can be found here). Using this class you can get friendly URL using the following code:

   1: string url = "";
   2: if (TaxonomyNavigationContext.Current != null &&
   3:     TaxonomyNavigationContext.Current.HasFriendlyUrl)
   4: {
   5:     url = SPUtility.GetFullUrl(SPContext.Current.Site,
   6:         TaxonomyNavigationContext.Current.ResolvedDisplayUrl); 
   7: }

If you are on the page with real URL http://example.com/products-site/info-site/pages/default.aspx this code will return friendly URL (e.g. http://example.com/products/info) and you will be able to use it in your code.

1 comment: