10/03/2011

Get the current URL in a SharePoint page or web part

 

Just a quick note on getting the URL of the current page in a SharePoint C# project.

 

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:

Note to spammers!

Spammers, don't waste your time... all posts are moderated. If your comment includes unrelated links, is advertising, or just pure spam, it will never be seen.