Getting page URLs in SharePoint sites is a bit different from normal ASP.NET sites, this article shows some examples about how to use them.

In normal asp.net site:

e.g. If we got a URL like http://localhost:81/cuisine/french/default.aspx, then we can use the below code to get URL objects.

  • HttpContext.Current.Request.Url.AbsolutePath
    output:
    /cuisine/french/default.aspx
  • HttpContext.Current.Request.Url.AbsoluteUri
    output:
    http://localhost:81/cuisine/french/default.aspx

  • HttpContext.Current.Request.Url.Host
    output:
    localhost

In SharePoint site:

As SharePoint is built on asp.net, so we can still use the above URL object models in SharePoint pages, but there are some specific SharePoint object model we can use to handle URLs:

e.g. http://localhost:81/cuisine/french/pages/default.aspx
This URL is referring to a SharePoint web page item located under we site http://localhost:81/cuisine/french | Pages library.

  • web.ServerRelativeUrl
    output:
    /cuisine/french

  • web.Url
    output:
    http://localhost:81/cuisine/french

  • site.Url  (root site)
    output:
    http://localhost:81

  • ListItem.Url (web page item)
    output:
    pages/default.aspx

  • When you get a file object (document or web page) in your code, you can also try to refer ServerUrl and FileRef property to get it’s URL values.
    Try
    r.Field<string>("ServerUrl") + r.Field<string>("FileRef").Substring(r.Field<string>("FileRef").IndexOf(";#") + 2)
    see what you can get 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *