Convert a relative url to an absolute url in an ASP.NET page

Category ASP.Net Sub Category Page Interaction
Bookmark and Share
These functions will take a relative url and return the absolute url. The function ToAbsoluteUrlForced will force a protocol http or https. Useful when wanting to go back to http for instance after having a https login screen.
Copy Code
Public Function ToAbsoluteUrl(ByVal url As String) As String 'convert a relative url to an absolute url 'takes into account the standard ports for the protocols may be different to default 'uses the current request to work out protocol and port Dim Protocol As String = IIf(Request.IsSecureConnection, "https", "http").ToString Dim Port As String Dim PortToCheck As Int32 = Convert.ToInt32(IIf(Protocol = "http", 80, 443)) Port = IIf(Request.Url.Port = PortToCheck, "", _ String.Concat(":", Request.Url.Port)).ToString Return String.Format("{0}://{1}{2}{3}", _ Protocol, _ Request.Url.Host, _ Port, _ Page.ResolveUrl(url)) End Function Public Function ToAbsoluteUrlForced(ByVal url As String, _ ByVal SecurePort As Boolean, _ Optional ByVal httpPort As Int32 = 80, _ Optional ByVal httpsPort As Int32 = 443 _ ) As String 'convert a relative url to an absolute url 'force the 'need to set the ports used if different to standard 80 for http and 443 for https 'seeing you may want to force ssl and system doesn't know ssl port Dim Protocol As String = IIf(SecurePort, "https", "http").ToString Dim Port As String Dim PortToCheck As Int32 = Convert.ToInt32(IIf(Protocol = "http", httpPort, httpsPort)) If SecurePort Then Port = IIf(httpPort = 80, "", String.Concat(":", httpPort)).ToString Else Port = IIf(httpPort = 443, "", String.Concat(":", httpPort)).ToString End If Return String.Format("{0}://{1}{2}{3}", _ Protocol, _ Request.Url.Host, _ Port, _ Page.ResolveUrl(url)) End Function



Share the love
Bookmark and Share