Skip to content
/

Translating URLs using Alternate Access Mappings from code

With SharePoint it’s easy to configure multiple zones for your SharePoint Web Application. For example you have a Publishing Web Site with two zones.

  1. The authenticated CMS where editors can manage content: https://cms.int
  2. The anonymous website where everybody can view the content: http://www.ext

When the editors link to sites, pages, documents and images the URL will start with https://cms.int. After the content is published it’ll also be available on the anonymous site. Now most of the URLs will be automatically translated to corresponding zone URL and start with http://www.ext.

There are however some place this is not the case. You could try to use relative URLs but even that won’t fix every scenario.

Translate the URL using code

Facing this issue I had to translate the URLs myself. But I want to write minimal code. Lucky Microsoft has done most of the work for me.

On the you will find the . This “collection” is actually an instance of the and provides the .
And this is where the magic happens.

This method has an overload where you supply a Uri and a SPUrlZone. You can provide one of the values of the or you can provide the current zone.

To get your current zone you can use the static of the . This method requires a Uri so we provide the current one using the from the same class.

To wrap it all up I give you the code:

var originalUri = new Uri("https://cms.int/pages/default.aspx");

var zone = SPAlternateUrl.Lookup(SPAlternateUrl.ContextUri).UrlZone;

var translateUri = SPFarm.Local.AlternateUrlCollections
                                    .RebaseUriWithAlternateUri(originalUri, zone));

// When accessing from the authenticated zone
// translateUri == "https://cms.int/pages/default.aspx"

// When accessing from the anonymous zone
// translateUri == http://www.ext/pages/default.aspx

“Other” URLs

If you pass a URL which is not listed as an Alternate Access Mapping the method will return the original URL.

Leave a comment