I am writing code in my master page that examines the page's URL as shown in the browser

I have a web application at URL:


and many site collections within it like this:


The code snippet I am using to examine the URL is:

Uri uri = Context.Request.Url;
StringBuilder sb = new StringBuilder();

sb.Append(" uri.AbsolutePath = " + uri.AbsolutePath + "<br />");
sb.Append("uri.AbsoluteUri = " + uri.AbsoluteUri + "<br />");

When I navigate to any of the above site collections the returned path is as expected.

Full URL to Page: http://teams.sharepoint.org/sitecollections/site1/Pages/default.aspx

Output of code snippet:
    uri.AbsolutePath = /sitecollections/site1/Pages/default.aspx
    uri.AbsoluteUri = http://teams.sharepoint.org/sitecollections/site1/Pages/default.aspx

Now notice what is returned when I navigate to the site settings page for any of the site collections.

The URL to the site settings is:


But now the code snippet returns only the /_layouts/settings.aspx portion and does not return the '/sitecollections/site1/' portion of the URL.

uri.AbsolutePath = /_layouts/settings.aspx
uri.AbsoluteUri = http://teams.sharepoint.org/_layouts/settings.aspx

Why is that omitted? The omitted portion is the part that I need to examine and act on but it is not returned.

Thanks for reading

  • 2
    What version of SP are you using? – Eric Alexander Aug 14 '12 at 0:18
  • 2010 enterprise – ChiliYago Aug 14 '12 at 13:09

Looks like you're having the same problem faced here: Absolute URLs not working with Virtual Directories

Try something like this to check if the path contains a SharePoint mapped / virtual directory:

Uri uri = Context.Request.Url;
StringBuilder sb = new StringBuilder();

sb.Append(" uri.AbsolutePath = " + uri.AbsolutePath + "<br />");

if (uri.AbsolutePath.Substring(0, 2) == "/_")
    string absoluteUri = 
      HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +
      HttpContext.Current.Request.ApplicationPath +
    sb.Append("uri.AbsoluteUri = " + absoluteUri + "<br />");
    sb.Append("uri.AbsoluteUri = " + uri.AbsoluteUri + "<br />");


Just make sure you test it, because I didn't.


For SharePoint 2010, you can use the SharePoint client object model to return the URL of the Site collection:

ClientContext clientContext = new ClientContext(siteUrl);
Site siteCollection = clientContext.Site;

var url = site.Url + "/_layouts/settings.aspx";

The MSDN article for the Client OM is here: http://msdn.microsoft.com/en-us/library/ee857094.aspx

  • 2
    Seems very unnatural to use the client side object model for code that executes server side. Seems like there should be a server side call that will do what I want. I appreciate the help though. – ChiliYago Aug 14 '12 at 17:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.