How to get the root url of the current site
16 Jan 2007I have situations where I need the domain name and the application path of the current page (request ).
if the current request was http://www.myserver.com/website1/page.aspx
I need http://www.myserver.com/website1. Though the web.config can store this setting, I don’t want to change the config each time I move the site between servers.
So here is a little function I wrote.
Request.Url.AbsoluteUri gives http://www.myserver.com/website1/page.aspx
Request.ApplicationPath gives /website1/. Subtract page.aspx from http://www.myserver.com/website1/page.aspx
public static string GetSiteUrl() {
if (HttpContext.Current.Request.ApplicationPath == “/”) {
return “/”
}
string url = HttpContext.Current.Request.Url.AbsoluteUri;
int end = url.IndexOf(HttpContext.Current.Request.ApplicationPath) +
HttpContext.Current.Request.ApplicationPath.Length;
url = url.Substring(, end);
return url;
}