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

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

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.


Request.Url.GetLeftPart(UriPartial.Authority)

This is included scheme.