EPiServer7.x: Get Aboslute Url from page

Sometimes you need an absolute url from a page within EPiServer.

Dejan Caric made this nice HowTo: http://www.dcaric.com/blog/episerver-how-to-get-external-page-url

Here the same code is put in an extension method and a method including wanted language is added:

        public static string GetExternalUrl(this PageReference pageReference)
        {
            var internalUrl = UrlResolver.Current.GetUrl(pageReference);
            var externalUrl = ExternalUrl(internalUrl);

            return externalUrl;
        }

        public static string GetExternalUrl(this PageReference pageReference, string languageName)
        {
            var internalUrl = UrlResolver.Current.GetUrl(pageReference, languageName);
            var externalUrl = ExternalUrl(internalUrl);

            return externalUrl;
        }

        private static string ExternalUrl(string internalUrl)
        {
            var url = new UrlBuilder(internalUrl);
            Global.UrlRewriteProvider.ConvertToExternal(url, null, Encoding.UTF8);

            string externalUrl = HttpContext.Current == null
                ? UriSupport.AbsoluteUrlBySettings(url.ToString())
                : HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + url;
            return externalUrl;
        }

Then you could fetch currentPage within a controller like here

EPiServer 7 : How do I get the “CurrentPage” from a controller ?

var pageRouteHelper = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance();

//Getting A Page Reference
var pageReference = pageRouteHelper.PageLink;

//Getting The Page Object
var currentPage = pageRouteHelper.Page;

//Getting The Page Object for the StartPage
var startPage = SiteDefinition.Current.StartPage

//Getting A Page Reference
var currentPageRef = currentPage.ToPageReference()

So with your Page Reference use the extensionmethod GetExternalUrl()

var extUrl = currentPageRef.GetExternalUrl();

//Switch to other language
var extUrlDe = currentPageRef.GetExternalUrl("de");

//Redir
System.Web.HttpContext.Current.Response.Redirect(extUrlDe, true);

Other links:

The End

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: