Tuesday, February 8, 2011

Getting SharePoint Web Application URL Using SPAlternateUrl

By using SPAlternateURL object, you can get the URL or SharePoint 2010 Web Application since the alternate access mappings are associated with a Web Application. Sample code is provided below:

public static string GetWebAppURL(SPWebApplication oWebApp, SPUrlZone urlZone)
{
    string retVal = string.Empty;
    try
    {
        foreach (SPAlternateUrl altUrl in oWebApp.AlternateUrls)
        {
            if (altUrl.UrlZone == urlZone)
            {
                retVal = altUrl.Uri.ToString();
                break;
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return retVal;
}

public static string GetWebAppURL(SPSite oSite, SPUrlZone urlZone)
{
    string retVal = string.Empty;
    SPWebApplication oWebApp = null;
    try
    {
        if ((oWebApp = oSite.WebApplication) != null)
            retVal = GetWebAppURL(oWebApp, urlZone);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return retVal;
}

public static string GetWebAppURL(SPWeb oWeb, SPUrlZone urlZone)
{
    string retVal = string.Empty;
    SPWebApplication oWebApp = null;
    try
    {
        if(( oWebApp = oWeb.Site.WebApplication)!=null)
            retVal = GetWebAppURL(oWebApp, urlZone);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return retVal;
}

In order to call these functions, you need to pass either SPWebApplication, SPSite or SPWeb object and specify the SPUrlZone enumeration which has the following originating zone of a request:

  • Default - Specifies the default zone used for requests unless another zone is specified.
  • Intranet - Specifies an intranet zone.
  • Internet - Specifies an Internet zone.
  • Custom - Specifies a custom zone.
  • Extranet - Specifies an extranet zone.

No comments: