How to get current domain name in ASP.NET

I want to get the current domain name in 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

I want to get

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


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 from because a webserver could be configured to serve a different site for compared to, 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.