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.
- The authenticated CMS where editors can mange content: http://cms.int
- 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 http://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 wanted to write minimal code. Lucky Microsoft has done most of the work for me.
On the SPFarm Class you will find the AlternateUrlCollections Property. This “collection” is actually an instance of the SPAlternateUrlCollectionManager Class and provides the RebaseUriWithAlternateUri Method. 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 SPUrlZone Enumeration or you can provide the current zone.
To get your current zone you can use the static Lookup Method of the SPAlternateUrl Class. This method requires a Uri so we provide the current one using the ContextUri Property from the same class.
To wrap it all up I give you the code:
var originalUri = new Uri("http://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 == "http://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.




One Comment
Leave a commentTrackbacks and Pingbacks