Friday, October 26, 2012

Get the current URL in a SharePoint page or web part

 

Three ways:

#1 (preferred if there is also a query string in the URL)

   string url = Request.Url.AbsoluteUri;

#2

   string url = "http://" + Request.ServerVariables["SERVER_NAME"] + Request.ServerVariables["URL"];

#3 (preferred for web parts - see below)

   string url = SPContext = " + SPContext.Current.Web.Url + "/" + SPContext.Current.File.Url;

Notes:

#1 will return the query string, while #2 and #3 will not.

#1 and #2 will give you odd results when used in a Layouts application page:

URL of page:
  http://intranet/sites/training/_layouts/SharePointProject3/ApplicationPage1.aspx

Returned from both #1 and #2:
  http://intranet/_layouts/SharePointProject3/ApplicationPage1.aspx

#2 when used in a web part will need System.Web.HttpContext.Current.Request:

"http://" + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + System.Web.HttpContext.Current.Request.ServerVariables["URL"];

No comments:

Post a Comment