tags:

views:

1451

answers:

7

Let's say I'm hosting a website at http://www.foobar.com.

Is there a way I can programmatically ascertain "http://www.foobar.com/" in my code behind (i.e. without having to hardcode it in my web config)?

+5  A: 

HttpContext.Current.Request.Url can get you all the info on the URL. And can break down the url into its fragments.

JoshBerke
Hmm why the down vote?
JoshBerke
Yes, why the down vote? Don't see something marked as the answer -and- downvoted often. :/
Zack
evil voters lurk among us
Saul Dolgin
+1  A: 

To get the entire request URL string:

HttpContext.Current.Request.Url

To get the www.foo.com portion of the request:

HttpContext.Current.Request.Url.Host

Note that you are, to some degree, at the mercy of factors outside your ASP.NET application. If IIS is configured to accept multiple or any host header for your application, then any of those domains which resolved to your application via DNS may show up as the Request Url, depending on which one the user entered.

Rex M
+1  A: 
string hostUrl = Request.Url.Scheme + "://" + Request.Url.Host; //should be "http://hostnamehere.com"
blesh
A: 

C# Example Below:

string scheme = "http://";
string rootUrl = default(string);
if (Request.ServerVariables["HTTPS"].ToString().ToLower() == "on")
{
  scheme = "https://";
}
rootUrl = scheme + Request.ServerVariables["SERVER_NAME"].ToString();
Saul Dolgin
A: 
string domainName = Request.Url.Host
Sk93
+1  A: 

For anyone still wondering, a more complete answer is available at http://devio.wordpress.com/2009/10/19/get-absolut-url-of-asp-net-application/.

public string FullyQualifiedApplicationPath
{
  get
  {
    //Return variable declaration
    string appPath = null;

    //Getting the current context of HTTP request
    HttpContext context = HttpContext.Current;

    //Checking the current context content
    if (context != null)
    {
      //Formatting the fully qualified website url/name
      appPath = string.Format("{0}://{1}{2}{3}",
        context.Request.Url.Scheme,
        context.Request.Url.Host,
        context.Request.Url.Port == 80
          ? string.Empty : ":" + context.Request.Url.Port,
        context.Request.ApplicationPath);
    }
    if (!appPath.EndsWith("/"))
      appPath += "/";
    return appPath;
  }
}
Brian Hasden
A: 
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
George