是否可以在不附加http://或https://(即协议)的情况下将外部URL分配给HyperLink? [英] Is there a way to assign an external URL to a HyperLink without appending http:// or https:// (ie, the protocol)?

查看:120
本文介绍了是否可以在不附加http://或https://(即协议)的情况下将外部URL分配给HyperLink?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的HyperLink定义如下:

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

我可以将http://附加到URL,但这不是首选方法,因为该URL可由用户维护.如果用户将URL保存为http://www.google.com,则URL最终看起来像http://http://www.google.com.我知道我可以从URL中剥离http://,然后将其重新添加以确保它不会出现两次,但这是我想避免编写的额外的代码/帮助程序方法.

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.

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

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)

更新,我知道我特别问过如何在不将协议附加到URL的情况下执行此操作,但是似乎没有其他方法可以执行此操作.选定的答案将我带到了该解决方案:

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

这很棒,因为如果用户仅输入www.google.com,它将在URL后面附加http://.如果用户提供协议(http,https,ftp等),它将保留它.

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.

推荐答案

使用Uri类并进行相应处理:

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;

这篇关于是否可以在不附加http://或https://(即协议)的情况下将外部URL分配给HyperLink?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆