[SOLVED] How do I get the site root URL?


I want to get the absolute root Url of an ASP.NET application dynamically. This needs to be the full root url to the application in the form: http(s)://hostname(:port)/

I have been using this static method:

public static string GetSiteRootUrl()
    string protocol;

    if (HttpContext.Current.Request.IsSecureConnection)
        protocol = "https";
        protocol = "http";

    StringBuilder uri = new StringBuilder(protocol + "://");

    string hostname = HttpContext.Current.Request.Url.Host;


    int port = HttpContext.Current.Request.Url.Port;

    if (port != 80 && port != 443)

    return uri.ToString();

BUT, what if I don’t have HttpContext.Current in scope?
I have encountered this situation in a CacheItemRemovedCallback.


I’ve solved this by adding a web.config setting in AppSettings (“SiteRootUrl”). Simple and effective, but yet another config setting to maintain.

Answered By – saille

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *