I have tried many ways to get the root/base url of a website. A static approach to this is to store it in the web.config appsettings section and calling it in code.
<appSettings>
<add key="RootUrl" value="http://www.mydotnetworld.com"/>
</appSettings>
string rootUrl = ConfigurationManager.AppSettings["RootUrl"];
This isnt convenient when you are working locally and the port number might change. Another way is to call a method to get the base/root of the website. I have seen numerous ways to do this and most of them had flaws. I created my own that I use in every project and hasnt failed me yet. It works in any development environment.
public static string RootUrl
{
get
{
HttpContext context = HttpContext.Current;
string executionPath = context.Request.ApplicationPath;
return string.Format("{0}://{1}{2}", context.Request.Url.Scheme,
context.Request.Url.Authority,
executionPath.Length == 1 ? string.Empty : executionPath);
}
}
I place this function inside a utility class and call it wherever the base/url is needed. It also comes in handy within javascript.
var rooUrl = <%= Utility.RootUrl %>;