105

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)?

Jon Seigel
  • 12,251
  • 8
  • 58
  • 92
core
  • 32,451
  • 45
  • 138
  • 193

14 Answers14

186
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);

Uri::GetLeftPart Method:

The GetLeftPart method returns a string containing the leftmost portion of the URI string, ending with the portion specified by part.

UriPartial Enumeration:

The scheme and authority segments of the URI.

d.danailov
  • 9,594
  • 4
  • 51
  • 36
George
  • 7,864
  • 5
  • 29
  • 25
122

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
        var appPath = string.Empty;

        //Getting the current context of HTTP request
        var 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
  • 4,050
  • 2
  • 31
  • 37
  • 4
    Worked perfectly. If the site is http://server:8080/MySiteName, it gets it correctly. – Michael La Voie May 19 '11 at 17:43
  • 2
    Thanks for sharing actual code instead of a link somewhere else. – theJerm Jan 02 '13 at 18:35
  • No problem. I've run into answers that include links to other sites and it's frustrating when the link is broken and then I have to search the Google cache or Wayback Machine for the content. – Brian Hasden Jan 02 '13 at 18:51
  • 2
    context.Request.Url.Port == 80 will cause problems within HTTPS – Evgenyt Feb 05 '13 at 14:51
  • You're right. It should be checking for both 80 and 443, but I don't believe specifying port 443 and https as the scheme will hurt anything. – Brian Hasden Feb 06 '13 at 15:11
  • 7
    Attention! Not work for https. For https need to replace `context.Request.Url.Port == 80` by `(context.Request.Url.Port == 80 && context.Request.Url.Scheme == "http") || (context.Request.Url.Port == 443 && context.Request.Url.Scheme == "https")` or use answer below – razon Sep 22 '14 at 13:56
  • 1
    Works also for localhost (if you are testing localy). If you don't need port, you can use "http://" + HttpContext.Current.Request.Url.Host; – CyberHawk Sep 24 '15 at 08:00
81

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

JoshBerke
  • 66,142
  • 25
  • 126
  • 164
  • 4
    Yes, why the down vote? Don't see something marked as the answer -and- downvoted often. :/ – Zack Jul 31 '09 at 20:41
  • 4
    I also do not like this answer. blesh has given the right one and this should have been marked as the answer... – Michal B. Nov 27 '11 at 15:50
  • -1 - Request.Url often gives a url such as "/folder1/folder2" and excludes the domain altogether. – Justin Apr 03 '12 at 01:34
  • 4
    @Justin: Request.Url gives you a Uri object which has all the pieces broken down for you. It shouldn't be giving you a string. At least not in the version of .net I am using – JoshBerke Apr 04 '12 at 19:37
  • 9
    This answer could be improved by adding the code that makes it work like the answer below that has more votes up... – theJerm Dec 20 '12 at 22:55
  • I downvoted because although it points to some possible implementation of the answer it is not an answer. Consider these cases: 1) When the root of the application is other than "/", 2) when the request URI includes the port, 3) differentiating between HTTPS and HTTP... – Isaac Llopis Aug 28 '14 at 15:20
  • @IsaacLlopis: Opp didn't ask for root of application he asked for Root Domain, I don't understand why is the port an issue? Try Request.Url.Port. Hmm Also it gives you the Schema. In fact look at all the other answers they all use the same thing. I pointed the opp at how to find the info. So he could craft his own solution – JoshBerke Aug 28 '14 at 20:02
  • George's answer should be marked as correct one - this one does not work in every case - e.g. port number in my case – fubo Mar 18 '15 at 09:38
  • @fubo HttpContext.Current.Request.Url.Port gives you the port And for Issac Yes I could have said HttpContext.Current.Request.Url.Host or HttpContext.Current.Request.Url.Authority instead I pointed the Opp to the documentation for the Url class which gave him all the info he needed. – JoshBerke Mar 22 '15 at 16:05
  • Potential host header injection. – Bose_geek Nov 16 '17 at 08:44
  • HttpContext.Current.Request.Url goes well inside controllers but in case you use it in a startup the Url looses important info. It returns http instead of https, 127.0.0.1 instead of custom origin and app name, port 80 instead of https specific (e.g. 443) – Alex Valchuk Nov 29 '18 at 11:57
  • So all the answers here seem different from what worked for me. Is it the difference between asp.net and the core version? Request.Host.ToString() works for me. – ahong May 21 '19 at 17:06
40

If example Url is http://www.foobar.com/Page1

HttpContext.Current.Request.Url; //returns "http://www.foobar.com/Page1"


HttpContext.Current.Request.Url.Host; //returns "www.foobar.com"


HttpContext.Current.Request.Url.Scheme; //returns "http/https"


HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority); //returns "http://www.foobar.com"
Dheeraj Palagiri
  • 1,829
  • 3
  • 23
  • 46
30
string hostUrl = Request.Url.Scheme + "://" + Request.Url.Host; //should be "http://hostnamehere.com"
Ben Lesh
  • 107,825
  • 47
  • 247
  • 232
16

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
  • 142,167
  • 33
  • 283
  • 313
6
Match match = Regex.Match(host, "([^.]+\\.[^.]{1,3}(\\.[^.]{1,3})?)$");
string domain = match.Groups[1].Success ? match.Groups[1].Value : null;

host.com => return host.com
s.host.com => return host.com

host.co.uk => return host.co.uk
www.host.co.uk => return host.co.uk
s1.www.host.co.uk => return host.co.uk

NQuenault
  • 69
  • 1
  • 1
4

--Adding the port can help when running IIS Express

Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port
JonathanC
  • 180
  • 7
3
string domainName = Request.Url.Host
Sk93
  • 3,676
  • 3
  • 37
  • 67
3

I know this is older but the correct way to do this now is

string Domain = HttpContext.Current.Request.Url.Authority

That will get the DNS or ip address with port for a server.

idlehands23
  • 326
  • 2
  • 10
3

This works also:

string url = HttpContext.Request.Url.Authority;

Alexander_F
  • 2,831
  • 3
  • 28
  • 61
1

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
  • 8,624
  • 4
  • 37
  • 43
1

This will return specifically what you are asking.

Dim mySiteUrl = Request.Url.Host.ToString()

I know this is an older question. But I needed the same simple answer and this returns exactly what is asked (without the http://).

abatishchev
  • 98,240
  • 88
  • 296
  • 433
tomepenn
  • 93
  • 12
1
string host = Request.Url.Host;
Regex domainReg = new Regex("([^.]+\\.[^.]+)$");
HttpCookie cookie = new HttpCookie(cookieName, "true");
if (domainReg.IsMatch(host))
{
  cookieDomain = domainReg.Match(host).Groups[1].Value;                                
}