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

跟風遠走 提交于 2020-01-03 17:28:28

问题


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.


回答1:


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;


来源:https://stackoverflow.com/questions/20502526/is-there-a-way-to-assign-an-external-url-to-a-hyperlink-without-appending-http

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!