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.


Solution 1:

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}"

Solution 2:

As per this link a good starting point is:

Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host 

However, if the domain is http://www.domainname.com:500 this will fail.

Something like the following is tempting to resolve this:

int defaultPort = Request.IsSecureConnection ? 443 : 80;
Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host 
  + (Request.Url.Port != defaultPort ? ":" + Request.Url.Port : "");

However, port 80 and 443 will depend on configuration.

As such, you should use IsDefaultPort as in the Accepted Answer above from Carlos Muñoz.