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;


   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;



#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:

Returned from both #1 and #2:

#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.