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

<p>For instance:</p>

<p><a href="http://www.domainname.com/subdir/" rel="noreferrer">http://www.domainname.com/subdir/</a> should yield <a href="http://www.domainname.com" rel="noreferrer">http://www.domainname.com</a>
<a href="http://www.sub.domainname.com/subdir/" rel="noreferrer">http://www.sub.domainname.com/subdir/</a> should yield <a href="http://sub.domainname.com" rel="noreferrer">http://sub.domainname.com</a></p>

<p>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.</p>

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.