Friday, October 2, 2009

SPSite constructor may break AAM link translation

You can use Alternate Access Mappings (AAM) in SharePoint to host the same content on different URLs.

For example, you could have two web applications in the Default zone with the host names example.local and mysite.local, which you publish to the Internet zone using www.example.com and mysite.example.com respectively.

AAM will normally translate links in the HTML automatically, so if the end user is browsing on www.example.com (the Internet zone) the link to the My Site in the top right of the page will include the mysite.example.com host (as this URL is also from the Internet zone).

However, you may find that the default URLs are displayed in links generated by your custom code in web parts or controls, regardless of which zone you are in.

This will occur if you create a new SPSite object and only specify the URL of the site in the constructor. SharePoint will then treat all content returned from this object as being in the default zone and will not translate the links.

Ensure that when you create SPSite objects you specify the current zone in the constructor. If you don't do this, it will use the default zone (and the links retrieved from that object in Url properties, Image fields, Url fields, HTML content etc. will refer to that zone).

So, instead of doing this:

using (SPSite site = new SPSite(url))
{
...
}

Do this:

SPContext context = SPContext.Current;
// This context only exists when the code is executed from a web application. For code running from from console applications, STSADM extensions, and (potentially) event handlers, you may need to refer to a different context.
using (SPSite site = new SPSite(url, context.Zone))
{
...
}

No comments:

Post a Comment