How to Get Base URL in ASP.NET using C#
by
Doug
Updated November 20, 2011
Examples of two ways to get the Base Url in C#.
If you do any sort of ASP.NET programming there usually comes a time when you need to get a websites Base URL. The following shows two examples, the first example shows how to get the Base Site Url using C#, which can be used for getting both the localhost base url address and the actually domain name address when the website is live, so the code will work correctly locally and when hosted on a production environment. The second example shows how to get the Base Virtual Application Root Path on the Server which might be used if you need to directly access files and/ or directories using the Server.MapPath() method.
Solution for getting the Base Site Url in ASP.net using C#:
public static string BaseSiteUrl
{
get
{
HttpContext context = HttpContext.Current;
string baseUrl = context.Request.Url.Scheme + "://" + context.Request.Url.Authority + context.Request.ApplicationPath.TrimEnd('/') + '/';
return baseUrl;
}
}
Example below shows use of "BaseSiteUrl" (For this example, the BaseSiteUrl is located in the Utilities class):
string siteLink = Utilities.BaseSiteUrl;
The "BaseSiteUrl" will get the full base url of a website, for example: https://www.gotknowhow.com/
Solution for getting the Base Virtual Application Root Path on the Server:
public static string BaseVirtualAppPath
{
get
{
HttpContext context = HttpContext.Current;
string url = context.Request.ApplicationPath;
if (url.EndsWith("/"))
return url;
else
return url + "/";
}
}
Example below shows use of "BaseVirtualAppPath":
string dirPath = "media/article/images/2009/01/27/";
HttpContext context = HttpContext.Current;
string dirUrl = Utilities.BaseVirtualAppPath + dirPath;
string dirFullPath = context.Server.MapPath(dirUrl);
The "BaseVirtualAppPath" will get the Base Virtual Application Root Path on the Server, for example it might return: /GotKnowHow/ if your application is named "GotKnowHow"