Jatin Gadhiya Jatin Gadhiya - 1 month ago 6
ASP.NET (C#) Question

How to get current domain name in ASP.NET

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:5858
but 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.

Dai Dai
Answer

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.

Comments