Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to assign an external URL to a HyperLink without appending http:// or https:// (ie, the protocol)?

I have a HyperLink defined like so:

<asp:HyperLink ID="hltest" runat="server"></asp:HyperLink>

In my code, I do this:

hltest.NavigateUrl = "www.google.com"

However, the actual link looks like this:

http://localhost:53305/www.google.com

I can append http:// to the URL, but this not the preferred method because this URL is maintainable by the user. If the user saves the URL as http://www.google.com then the URL will end up looking like http://http://www.google.com. I know that I can strip http:// from the URL and then add it back to ensure that it doesn't show up twice, but this is extra code/helper method that I would like to avoid writing.

Edit: This is the type of code I am trying to avoid having to write:

hltest.NavigateUrl = "http://" & "hTTp://www.google.com".ToLower().Replace("http://", String.Empty)

Update I know I specifically asked how to do this without appending the protocol to the URL, but it looks like there's just no other way to do it. The selected answer brought me to this solution:

Function GetExternalUrl(Url As String) As String

    Return If(New Uri(Url, UriKind.RelativeOrAbsolute).IsAbsoluteUri, Url, "http://" & Url)

End Function

This is great because, if the user enters just www.google.com, it will append http:// to the URL. If the user provides the protocol (http, https, ftp, etc), it will preserve it.

like image 277
oscilatingcretin Avatar asked Feb 14 '23 10:02

oscilatingcretin


1 Answers

Use the Uri class and handle it accordingly:

Uri uri = new Uri( userProvidedUri, UriKind.RelativeOrAbsolute );
if( !uri.IsAbsolute ) hltest.NavigateUrl = "http://" + userProvidedUri;
else hltest.NavigateUrl = userProvidedUri;
like image 176
Dai Avatar answered Feb 16 '23 22:02

Dai