As part of my Search Engine friendly SiteMap.xml generator (using a HttpHandler - expect a blog post shortly...) I needed to output the friendly URL for each page in the site. However a call to PageData.LinkURL returns the actual link to the page (example shown below), not a "friendly" one that gets displayed in the browser address bar, or in any Hyperlink within the site.
/MySite/Default.aspx?id=26&epslanguage=en-GB
I had a look through the EPiServer documentation and couldn't find anything obvious so resorted to creating my own method to do it (shown below). Simply pass the relevant PageData object to the function and it will return the page's Friendly URL. e.g. /mysite/en-GB/about-us
/// <summary>
/// Get a friendly URL for the given PageData object
/// </summary>
/// <param name="pd">The page to get the Friendly URL from</param>
/// <param name="Absolute">Return an absolute path</param>
/// <returns>The friendly Url for the given PageData object</returns>
public static string GetFriendlyUrl(PageData pd, bool Absolute)
{
UrlBuilder url = new UrlBuilder(pd.LinkURL);
//Call UrlRewriteProvider's ConvertToExternal method
EPiServer.Global.UrlRewriteProvider.ConvertToExternal(
url,
pd.PageLink,
UTF8Encoding.UTF8);
if (!Absolute)
return url.ToString();
else
return StringUtilities.GetBaseUrl() + url.ToString();
}
If you want to use Absolute paths you'll need to add this method:
/// <summary>
/// Gets the base URL from the current Context.
/// </summary>
/// <returns></returns>
public static string GetBaseUrl()
{
//First get the current port
string Port = HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
if (Port == null || Port == "80" || Port == "443")
Port = "";
else //Its not a standard port so add it
Port = ":" + Port;
//Now get the protocol (http or https)
string Protocol = HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];
if (Protocol == null || Protocol == "0")
Protocol = "http://";
else
Protocol = "https://";
//Finally combine the protocol, sever name and port
string url = Protocol + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + Port;
//EPiServer's url start with a / so remove the url if (when) it contains one
if (url.EndsWith("/"))
return url.Remove(url.LastIndexOf("/"));
else
return url;
}