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

Issue

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";
    else
        protocol = "http";

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

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

    uri.Append(hostname);

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

    if (port != 80 && port != 443)
    {
        uri.Append(":");
        uri.Append(port.ToString());
    }

    return uri.ToString();
}

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

Solution

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 *