Javascript 在VB.net中检查URL的有效性
我正在制作一个表单,要求用户提供文件的URL。我需要检查这个URL是否真的指向某个东西。我使用带有服务器端验证的CustomValidator。代码如下:Javascript 在VB.net中检查URL的有效性,javascript,asp.net,vb.net,Javascript,Asp.net,Vb.net,我正在制作一个表单,要求用户提供文件的URL。我需要检查这个URL是否真的指向某个东西。我使用带有服务器端验证的CustomValidator。代码如下: Protected Sub documentUrlValide_ServerValidate (ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles documentUrlValide.ServerVal
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,这里有一个非常好的方法: 编辑:那么这些方法中的一种怎么样 搜索是否存在URL?开
为什么不改用这个方法呢?我将您的代码放到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()
谷歌
与其读取流,不如测试HTTP状态代码?我相信这是response.StatusCode。您要查找的值是200,或者可能是300s重定向中的某个值。我在我的应用程序中输入了这段代码,但它不起作用。我想知道这是否与我办公室的防火墙规则有关。我来看看这个,测试了一下,没有任何变化。但philip证明了我的代码应该是可以工作的。我的应用程序不使用jQuery,我不会仅仅因为这个原因而添加它。但我必须能够用常规的JS实现这一点。这就是我计划用来改进我的验证机制的事情。不幸的是,我现在还不太清楚,我的代码在返回状态代码之前抛出了一个异常。