What is the fastest way to get the absolute uri for the root of an application in asp.net?

What is the easiest way to get: http://www.[Domain].comin asp.net?

It seems that there is no one method that can do this, the only way I know is to do some string acrobatics on server variables or Request.Url. Is anyone

+5
source share
10 answers

You can do it as follows:

string.Format("{0}://{1}:{2}", Request.Url.Scheme, Request.Url.Host, Request.Url.Port)

And you get the general syntax of the URI <protocol>: // <host>: <port>

+2
source

We can use Uri and its baseUri constructor:

  • new Uri(this.Request.Url, "/") for the root of the website
  • new Uri(this.Request.Url, this.Request.ResolveUrl("~/")) for the root of the website
+3
source

- .

System.Web.HttpContext.Current.Server.ResolveUrl("~/")

. , , .

Edit

!

+2

, CMS , String.Format Page.Request. . , , :

String baseURL = string.Format(
   (Request.Url.Port != 80) ? "{0}://{1}:{2}" : "{0}://{1}", 
    Request.Url.Scheme, 
    Request.Url.Host, 
    Request.Url.Port)
+2
System.Web.UI.Page.Request.Url
+1
this.Request.Url.Host
+1

:

string FullApplicationPath {
    get {
        StringBuilder sb = new StringBuilder();
        sb.AppendFormat("{0}://{1}", Request.Url.Scheme, Request.Url.Host);

        if (!Request.Url.IsDefaultPort)
            sb.AppendFormat(":{0}", Request.Url.Port);

        if (!string.Equals("/", Request.ApplicationPath))
            sb.Append(Request.ApplicationPath);

        return sb.ToString();
    }
}
+1

http/https, .

'Returns current page URL 
Function fullurl() As String
    Dim strProtocol, strHost, strPort, strurl, strQueryString As String
    strProtocol = Request.ServerVariables("HTTPS")
    strPort = Request.ServerVariables("SERVER_PORT")
    strHost = Request.ServerVariables("SERVER_NAME")
    strurl = Request.ServerVariables("url")
    strQueryString = Request.ServerVariables("QUERY_STRING")

    If strProtocol = "off" Then
        strProtocol = "http://"
    Else
        strProtocol = "https://"
    End If

    If strPort <> "80" Then
        strPort = ":" & strPort
    Else
        strPort = ""
    End If

    If strQueryString.Length > 0 Then
        strQueryString = "?" & strQueryString
    End If

    Return strProtocol & strHost & strPort & strurl & strQueryString
End Function
0

- , , .

- .

So, I came up with the following solution: it works on a local host with or without virtual directories and, of course, on IIS sites.

string.Format("{0}://{1}:{2}{3}", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, ResolveUrl("~")
0
source

Combining the best of what I saw on this issue, this applies to:

  • http and https
  • standard ports (80, 443) and non-standard
  • application hosted in a subfolder root

    string url = String.Format(
        Request.Url.IsDefaultPort ? "{0}://{1}{3}" : "{0}://{1}:{2}{3}",
        Request.Url.Scheme, Request.Url.Host,
        Request.Url.Port, ResolveUrl("~/"));
    
0
source

All Articles