How can I get the baseurl of site?

Jaggu picture Jaggu · Sep 14, 2011 · Viewed 248.6k times · Source

I want to write a little helper method which returns the base URL of the site. This is what I came up with:

public static string GetSiteUrl()
{
    string url = string.Empty;
    HttpRequest request = HttpContext.Current.Request;

    if (request.IsSecureConnection)
        url = "https://";
    else
        url = "http://";

    url += request["HTTP_HOST"] + "/";

    return url;
}

Is there any mistake in this, that you can think of? Can anyone improve upon this?

Answer

Frank Allenby picture Frank Allenby · Sep 14, 2011

Try this:

string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + 
    Request.ApplicationPath.TrimEnd('/') + "/";