Search code examples
asp.netasp.net-mvcdomain-name

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

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