110

I want to get the current domain name in asp.net c#.

I am using this code.

string DomainName = HttpContext.Current.Request.Url.Host;

My URL is localhost:5858but it's returning only localhost.

Now, I am using my project in localhost. I want to get localhost:5858.

For another example, when I am using this domain

www.somedomainname.com

I want to get somedomainname.com

Please give me an idea how to get the current domain name.

jordanhill123
  • 4,142
  • 2
  • 31
  • 40
Jatin Gadhiya
  • 1,955
  • 5
  • 23
  • 42
  • 1
    Hostname and domain name are 2 different things. Are you wanting a domain that is mapped to your specific IP address, or the hostname of the machine on which it runs? – Rob Goodwin Oct 04 '14 at 05:33
  • possible duplicate of [What's the best method in ASP.NET to obtain the current domain?](http://stackoverflow.com/questions/61817/whats-the-best-method-in-asp-net-to-obtain-the-current-domain) – Gitz Oct 04 '14 at 05:49
  • var base_url = "@Request.Url.GetLeftPart(UriPartial.Authority)@Url.Content("~/")" – Prince Prasad Aug 29 '18 at 11:58

13 Answers13

167

Try getting the “left part” of the url, like this:

string domainName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);

This will give you either http://localhost:5858 or https://www.somedomainname.com whether you're on local or production. If you want to drop the www part, you should configure IIS to do so, but that's another topic.

Do note that the resulting URL will not have a trailing slash.

Arturo Torres Sánchez
  • 2,751
  • 4
  • 20
  • 33
  • 8
    This should be the best answer in my opinion. – Andrew Jul 08 '16 at 21:07
  • 1
    This worked superbly for my needs. One small correction, however: when requesting the Authority part, the returned string will not include the trailing path delimiter. Thus: `http://localhost:60333` – Will Jun 06 '18 at 17:50
  • 1
    var base_url = "@Request.Url.GetLeftPart(UriPartial.Authority)@Url.Content("~/")" – Prince Prasad Jul 29 '18 at 13:08
  • 2
    This doesn't seem to be working on Asp.Net Core 2.2. I'm getting 'HttpContext' does not contain a definition for 'Current' and no accessible extension method 'Current' accepting a first argument of type 'HttpContext' could be found (are you missing a using directive or an assembly reference?). – Stian Jun 02 '19 at 19:12
  • @Stian Apparently there's another post already answering that: https://stackoverflow.com/questions/31243068/access-the-current-httpcontext-in-asp-net-core . This answers focus only on the URI part. – Arturo Torres Sánchez Jun 17 '19 at 14:35
  • HttpContext.Current.Request.Url.Host only returns localhost, not the port, this is the best answer. – live-love Feb 04 '22 at 01:50
  • Request is not available when there is no request e.g. in application startup methods, static class initializers ... – AaA Jan 05 '23 at 03:06
  • As @Stian wrote, this doesn't work in dotnet core latest version HttpRequest no longer contains any property called Url... – Brian Birtle May 31 '23 at 02:53
  • @BrianBirtle This answer is about the GetLefPart() method on any Uri object. If you need an HttpContext, see https://stackoverflow.com/questions/31243068/access-the-current-httpcontext-in-asp-net-core – Arturo Torres Sánchez May 31 '23 at 06:29
94

Using Request.Url.Host is appropriate - it's how you retrieve the value of the HTTP Host: header, which specifies which hostname (domain name) the UA (browser) wants, as the Resource-path part of the HTTP request does not include the hostname.

Note that localhost:5858 is not a domain name, it is an endpoint specifier, also known as an "authority", which includes the hostname and TCP port number. This is retrieved by accessing Request.Uri.Authority.

Furthermore, it is not valid to get somedomain.com from www.somedomain.com because a webserver could be configured to serve a different site for www.somedomain.com compared to somedomain.com, however if you are sure this is valid in your case then you'll need to manually parse the hostname, though using String.Split('.') works in a pinch.

Note that webserver (IIS) configuration is distinct from ASP.NET's configuration, and that ASP.NET is actually completely ignorant of the HTTP binding configuration of the websites and web-applications that it runs under. The fact that both IIS and ASP.NET share the same configuration files (web.config) is a red-herring.

Dai
  • 141,631
  • 28
  • 261
  • 374
62

Here is a screenshot of Request.RequestUri and all its properties for everyone's reference.

enter image description here

ThiagoPXP
  • 5,362
  • 3
  • 31
  • 44
  • Do the same thing when your breakpoint is in Global.Application_Start. Request object doesn't exist at that time! – AaA Jan 05 '23 at 03:07
20

You can try the following code :

 Request.Url.Host +
    (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port)
Rajeev Mehta
  • 820
  • 2
  • 10
  • 32
7

I use it like this in asp.net core 3.1

 var url =Request.Scheme+"://"+ Request.Host.Value;
Dharman
  • 30,962
  • 25
  • 85
  • 135
Zoha Shobbar
  • 446
  • 8
  • 17
6

www.somedomain.com is the domain/host. The subdomain is an important part. www. is often used interchangeably with not having one, but that has to be set up as a rule (even if it's set by default) because they are not equivalent. Think of another subdomain, like mx.. That probably has a different target than www..

Given that, I'd advise not doing this sort of thing. That said, since you're asking I imagine you have a good reason.

Personally, I'd suggest special-casing www. for this.

string host = HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);;

if (host.StartsWith("www."))
    return host.Substring(4);
else
    return host;

Otherwise, if you're really 100% sure that you want to chop off any subdomain, you'll need something a tad more complicated.

string host = ...;

int lastDot = host.LastIndexOf('.');

int secondToLastDot = host.Substring(0, lastDot).LastIndexOf('.');

if (secondToLastDot > -1)
    return host.Substring(secondToLastDot + 1);
else
    return host;

Getting the port is just like other people have said.

Matthew Haugen
  • 12,916
  • 5
  • 38
  • 54
1

HttpContext.Current.Request.Url.Host is returning the correct values. If you run it on www.somedomainname.com it will give you www.somedomainname.com. If you want to get the 5858 as well you need to use

HttpContext.Current.Request.Url.Port 
artm
  • 8,554
  • 3
  • 26
  • 43
1

the Request.ServerVariables object works for me. I don't know of any reason not to use it.

ServerVariables["SERVER_NAME"] and ServerVariables["HTTP_URL"] should get what you're looking for

pquest
  • 3,151
  • 3
  • 27
  • 40
PJ Leirer
  • 19
  • 2
1

You can try the following code to get fully qualified domain name:

Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host
Yogesh Patel
  • 818
  • 2
  • 12
  • 26
  • 4
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Dr Rob Lang Oct 26 '17 at 07:58
1

Here is a quick easy way to just get the name of the url.

            var urlHost = HttpContext.Current.Request.Url.Host;

            var xUrlHost = urlHost.Split('.');
            foreach(var thing in xUrlHost)
            {
                if(thing != "www" && thing != "com")
                {
                    urlHost = thing;
                }
            }
dstineback
  • 103
  • 2
  • 4
0

To get base URL in MVC even with subdomain www.somedomain.com/subdomain:

var url = $"{Request.Url.GetLeftPart(UriPartial.Authority)}{Url.Content("~/")}";
Ivan-San
  • 771
  • 1
  • 5
  • 22
0

string domainName = HttpContext.Request.Host.Value;

this line should solve it

AwadhJY
  • 1
  • 2
-1

Try this:

@Request.Url.GetLeftPart(UriPartial.Authority)

Hiren Patel
  • 317
  • 4
  • 7