Anders G. Nordby

Lead Consultant at Itera

Monthly Archives: April 2014

Getting an External URL in EPiServer 7.x

This seems like a pretty straight-forward task, but it’s actually harder than you could expect.
It’s such a basic need that I think it should have been built in.

Here is my working version (after many failed attemps):

private static string GetExternalUrl(IContent content)
{
    var urlResolver = ServiceLocator.Current.GetInstance();
    var internalUrl = urlResolver.GetUrl(content.ContentLink);
            
    var url = new UrlBuilder(internalUrl);
    Global.UrlRewriteProvider.ConvertToExternal(url, null, System.Text.Encoding.UTF8);

    var friendlyUrl = UriSupport.AbsoluteUrlBySettings(url.ToString());
    return friendlyUrl;
}

UPDATE (improved version from Ted Nybergs comment):

private static string GetExternalUrl(IContent content)
{
    var internalUrl = UrlResolver.Current.GetUrl(content.ContentLink);
            
    var url = new UrlBuilder(internalUrl);
    Global.UrlRewriteProvider.ConvertToExternal(url, null, System.Text.Encoding.UTF8);

    var friendlyUrl = UriSupport.AbsoluteUrlBySettings(url.ToString());
    return friendlyUrl;
}

UPDATE:
For those who think the GetUrl method will give me what I want… Take a look at the content of my ext variable here, and compare it to what the method will return! Nope, the GetUrl method does not give me the external URL:
friendlyUrl

Advertisements