加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 有没有办法将外部URL分配给HyperLink而不附加http:/

发布时间:2020-12-16 06:49:43 所属栏目:asp.Net 来源:网络整理
导读:我有一个像这样定义的HyperLink: asp:HyperLink ID="hltest" runat="server"/asp:HyperLink 在我的代码中,我这样做: hltest.NavigateUrl = "www.google.com" 但是,实际链接如下所示: http://localhost:53305/www.google.com 我可以将http://附加到URL,但
我有一个像这样定义的HyperLink:

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

在我的代码中,我这样做:

hltest.NavigateUrl = "www.google.com"

但是,实际链接如下所示:

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

我可以将http://附加到URL,但这不是首选方法,因为此URL可由用户维护.如果用户将网址保存为http://www.google.com,则该网址最终会显示为http:// http://www.google.com.我知道我可以从URL中删除http://然后将其添加回来以确保它不会显示两次,但这是我想避免编写的额外代码/帮助方法.

编辑:这是我试图避免写的代码类型:

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

更新我知道我特意询问如何在不将协议附加到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://附加到网址.如果用户提供协议(http,https,ftp等),它将保留它.

解决方法

使用Uri类并相应地处理它:

Uri uri = new Uri( userProvidedUri,UriKind.RelativeOrAbsolute );
if( !uri.IsAbsolute ) hltest.NavigateUrl = "http://" + userProvidedUri;
else hltest.NavigateUrl = userProvidedUri;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读