Navigation

Search

Categories

On this page

How to get the root url of the current site

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 148
This Year: 1
This Month: 0
This Week: 0
Comments: 42

Sign In
Pick a theme:

# Tuesday, January 16, 2007
Tuesday, January 16, 2007 11:17:33 AM (GMT Standard Time, UTC+00:00) ( .Net Web )

I 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(0, end);
            return url;
        }