What is the simplest way to get: http://www.[Domain].com in asp.net?
There doesn't seem to be one method which can do this, the only way I know is to do some string acrobatics on server variables or Request.Url. Anyone?
What is the simplest way to get: http://www.[Domain].com in asp.net?
There doesn't seem to be one method which can do this, the only way I know is to do some string acrobatics on server variables or Request.Url. Anyone?
You can use something like this.
System.Web.HttpContext.Current.Server.ResolveUrl("~/")
It maps to the root of the application. now if you are inside of a virtual directory you will need to do a bit more work.
Edit
Old posting contained incorrect method call!
You can do it like this:
string.Format("{0}://{1}:{2}", Request.Url.Scheme, Request.Url.Host, Request.Url.Port)
And you'll get the generic URI syntax <protocol>://<host>:<port>
I really like the way CMS handled this question the best, using the String.Format, and the Page.Request variables. I'd just like to tweak it slightly. I just tested it on one of my pages, so, i'll copy the code here:
String baseURL = string.Format(
(Request.Url.Port != 80) ? "{0}://{1}:{2}" : "{0}://{1}",
Request.Url.Scheme,
Request.Url.Host,
Request.Url.Port)
This method handles http/https, port numbers and query strings.
'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
I had to deal with something similar, I needed a way to programatically set the tag to point to my website root.
The accepted solution wasn't working for me because of localhost and virtual directories stuff.
So I came up with the following solution, it works on localhost with or without virtual directories and of course under IIS Websites.
string.Format("{0}://{1}:{2}{3}", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, ResolveUrl("~")
Combining the best of what I've seen on this question so far, this one takes care of:
application hosted in a sub-folder of the 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("~/"));