【发布时间】: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