Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best method in ASP.NET to obtain the current domain?

I am wondering what the best way to obtain the current domain is in ASP.NET?

For instance:

http://www.domainname.com/subdir/ should yield http://www.domainname.com http://www.sub.domainname.com/subdir/ should yield http://sub.domainname.com

As a guide, I should be able to add a url like "/Folder/Content/filename.html" (say as generated by Url.RouteUrl() in ASP.NET MVC) straight onto the URL and it should work.

like image 750
Matt Mitchell Avatar asked Sep 15 '08 03:09

Matt Mitchell


People also ask

Which method will get current application hosting 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.


1 Answers

Same answer as MattMitchell's but with some modification. This checks for the default port instead.

Edit: Updated syntax and using Request.Url.Authority as suggested

$"{Request.Url.Scheme}{System.Uri.SchemeDelimiter}{Request.Url.Authority}" 
like image 53
Carlos Muñoz Avatar answered Oct 13 '22 12:10

Carlos Muñoz