Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current domain name in ASP.NET

Tags:

c#

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

like image 625
Jatin Gadhiya Avatar asked Oct 04 '14 05:10

Jatin Gadhiya


1 Answers

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.

like image 142
Arturo Torres Sánchez Avatar answered Oct 06 '22 14:10

Arturo Torres Sánchez