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

Matt Mitchell picture Matt Mitchell · Sep 15, 2008 · Viewed 89k times · Source

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.

Answer

Carlos Muñoz picture Carlos Muñoz · May 21, 2010

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