asp.net - 有没有办法将外部 URL 分配给超链接而不附加 http ://or https://(ie, 协议(protocol))?

标签 asp.net hyperlink

我有一个像这样定义的超链接:

<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/

相关文章:

c# - 更新 ASP.NET 知识

c# - 如何对齐 Asp 单选按钮元素的列表项?

javascript - js 使用 css 格式隐藏/取消隐藏

php - 将 php 文件链接到 HTML 文件?

ruby-on-rails - 在Rails中未定义的局部变量或方法 `welcome_goodbye_path'?

javascript - 使用表单中的提交链接发送值

.net - 如何编辑 'bit'数据类型?

asp.net - 如何终止对 .net Web 服务的 javascript 异步调用?

asp.net - jQuery 的 ajax 导致 FireFox 中的整页刷新

html - Bootstrap Popover - 如何在文本弹出窗口中添加链接?