Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the site root URL?

Tags:

asp.net

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.

like image 657
saille Avatar asked May 02 '11 03:05

saille


People also ask

What is a site root URL?

A root URL is the start or index page of a domain on a web server. Colloquially, many users call the homepage the “root URL” as well.

What are the parts of a URL?

A URL consists of five parts: the scheme, subdomain, top-level domain, second-level domain, and subdirectory. Below is an illustration of the different parts of a URL. Let's break down this URL structure below.


3 Answers

For WebForms, this code will return the absolute path of the application root, regardless of how nested the application may be:

HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + ResolveUrl("~/") 

The first part of the above returns the scheme and domain name of the application (http://localhost) without a trailing slash. The ResolveUrl code returns a relative path to the application root (/MyApplicationRoot/). By combining them together, you get the absolute path of the web forms application.

Using MVC:

HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + Url.Content("~/") 

or, if you are trying to use it directly in a Razor view:

@HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)@Url.Content("~/") 
like image 195
saluce Avatar answered Sep 18 '22 12:09

saluce


You might try getting the raw URL and trimming off everything after the path forward slash. You could also incorporate ResolveUrl("~/").

like image 31
Jonathan Wood Avatar answered Sep 21 '22 12:09

Jonathan Wood


public static string GetAppUrl()
{
    // This code is tested to work on all environments
    var oRequest = System.Web.HttpContext.Current.Request;
    return oRequest.Url.GetLeftPart(System.UriPartial.Authority)
        + System.Web.VirtualPathUtility.ToAbsolute("~/");

}
like image 44
Denny Jacob Avatar answered Sep 19 '22 12:09

Denny Jacob