我有一个像这样定义的超链接:
<asp:HyperLink ID="hltest" runat="server"></asp:HyperLink>
在我的代码中,我这样做:
hltest.NavigateUrl = "www.google.com"
但是,实际的链接如下所示:
http://localhost:53305/www.google.com
我可以将 http://
附加到 URL,但这不是首选方法,因为该 URL 可由用户维护。如果用户将 URL 保存为 http://www.google.com
,则该 URL 最终将类似于 http://http://www.google.com
>。我知道我可以从 URL 中删除 http://
然后将其添加回来以确保它不会出现两次,但这是我想避免的额外代码/帮助程序方法写作。
编辑:这是我试图避免编写的代码类型:
hltest.NavigateUrl = "http://" & "hTTp://www.google.com".ToLower().Replace("http://", String.Empty)
更新 我知道我特别询问了如何在不将协议(protocol)附加到 URL 的情况下执行此操作,但看起来没有其他方法可以做到这一点。所选答案使我想到了这个解决方案:
Function GetExternalUrl(Url As String) As String
Return If(New Uri(Url, UriKind.RelativeOrAbsolute).IsAbsoluteUri, Url, "http://" & Url)
End Function
这很棒,因为如果用户仅输入 www.google.com
,它会将 http://
附加到 URL。如果用户提供协议(protocol)(http、https、ftp 等),它将保留它。
最佳答案
使用 Uri
类并进行相应处理:
Uri uri = new Uri( userProvidedUri, UriKind.RelativeOrAbsolute );
if( !uri.IsAbsolute ) hltest.NavigateUrl = "http://" + userProvidedUri;
else hltest.NavigateUrl = userProvidedUri;
关于asp.net - 有没有办法将外部 URL 分配给超链接而不附加 http ://or https://(ie, 协议(protocol))?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20502526/