GotKnowHow.com

How to Get Base URL in ASP.NET using C#

by


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: http://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"

 


0
3

3 Comments

anonymous by Hemanat Malav on 2/20/2010
It works for me, thanks
anonymous by Zafar on 2/3/2011
Thanks u'r article save my times
anonymous by SRJ on 6/9/2011
Good one !

Add your comment

by Anonymous - Already have an account? Login now!
Your Name:  

Comment:  
Enter the text you see in the image below
What do you see?
Can't read the image? View a new one.
Your comment will appear after being approved.

Ask a Question

140 characters left

Recent Articles

Follow Us...