【问题标题】:checking for URL validity in VB.net在 VB.net 中检查 URL 的有效性
【发布时间】:2010-12-14 15:41:42
【问题描述】:

我正在处理一种要求用户提供文件 URL 的表单。我需要检查该 URL 是否真的指向某些东西。我使用带有服务器端验证的 CustomValidator。这是代码:

Protected Sub documentUrlValide_ServerValidate
(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
Handles documentUrlValide.ServerValidate

    Try
        Dim uri As New Uri(args.Value)
        Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
        Dim response As HttpWebResponse = request.GetResponse()
        Dim stream As Stream = response.GetResponseStream()
        Dim reader As String = New StreamReader(stream).ReadToEnd()
        args.IsValid = True
    Catch ex As Exception
        args.IsValid = False
    End Try

End Sub

我用几个有效的 URL 对其进行了测试,没有一个通过测试,request.GetResponse() 总是抛出一个 WebException :“无法解析远程名称”。

这段代码有什么问题?

更新:

尽管我的代码显然没问题,但我无法在服务器端进行这项工作,因此我使用 javascript 同步 HTTP 请求在客户端运行它。这是代码(注意我的应用程序只被要求在IE上运行,由于Http请求调用不同,此代码在其他浏览器上不起作用)

function testURLValide(sender, args)
{
    var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    xmlhttp.open("HEAD", args.Value, false);
    xmlhttp.send(null);

    if (! (xmlhttp.status == 400 || xmlhttp.status == 404))
    {
        args.IsValid = true;
    }
    else
    {
        args.IsValid = false;
    }
}

【问题讨论】:

    标签: javascript asp.net vb.net


    【解决方案1】:

    我将您的代码放入 LINQPad 并对其进行了测试,它运行良好... 唯一的区别是 args.Value。

    Dim uri As New Uri("http://www.google.com")
    Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(uri)
    Dim response As System.Net.HttpWebResponse = request.GetResponse()
    Dim stream As Stream = response.GetResponseStream()
    Dim reader As String = New StreamReader(stream).ReadToEnd()
    
    reader.Dump()
    

    谷歌............

    【讨论】:

    • 我把这个确切的代码放在我的应用程序中,但它不起作用。我想知道这是否与我办公室的防火墙规则有关。我会看看这个。
    【解决方案2】:

    为什么不使用WebClient.DownloadString() 方法呢?

    【讨论】:

    • 经过测试,并没有改变任何东西。但 philip 证明我的代码无论如何都应该可以工作。
    【解决方案3】:

    不读取流,如何测试 HTTP 状态代码?我相信这是 response.StatusCode。您要查找的值是 200,或者可能是 300 的值(重定向)。

    【讨论】:

    • 这是我计划做的事情来改进我的验证机制。不幸的是,我目前还没有那么远,我的代码在返回状态码之前抛出了异常。
    【解决方案4】:

    如果您可以使用 javascript,这是一种非常好的方法:How to Test a URL in jQuery

    编辑:那么其中一种方法怎么样?

    搜索“网址是否存在?”在this page

    How to check if a URL exists in javascript

    Javascript to check if URL exist

    【讨论】:

    • 我的应用程序没有使用 jQuery,我不会仅仅因为这个原因添加它。但我必须能够用普通的 JS 做到这一点。
    猜你喜欢
    • 2011-04-17
    • 1970-01-01
    • 2015-03-20
    • 2014-08-17
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 2011-01-14
    相关资源
    最近更新 更多