I am working on a form in which users are asked to provide a file's URL. I need to check if that URL really points to something. I use a CustomValidator with server-side validation. Here is the code :
Protected Sub doc开发者_JAVA百科umentUrlValide_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
I tested it with several valid URLs, none passed the test, the request.GetResponse() always throws a WebException : "can not resolve distant name".
What is wrong with this code ?
Update :
I couldn't make this work server-side, despite my code apparently being fine, so I ran it client-side with a javascript synchronous HTTP request. Here is the code (note that my application is only requested to run on IE, this code won't work on other browsers dut to Http request calls being different)
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;
}
}
I put your code into LINQPad and tested it out and it worked just fine... The only difference is 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()
<!doctype html><html><head><meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"><title>Google</title>............
Why not use WebClient.DownloadString()
method instead?
Instead of reading the stream, how about testing for the HTTP Status Code? I believe it is response.StatusCode. The value you would look for would be 200, or possibly something in the 300s (redirect).
If you can use javascript, here's one really good way to do it: How to Test a URL in jQuery
Edit: How about one of these approaches then?
Search for "Does a URL exist?" on this page.
How to check if a URL exists in javascript
Javascript to check if URL exist
精彩评论