Note that there are some explanatory texts on larger screens.

plurals
  1. POchecking for URL validity in VB.net
    text
    copied!<p>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 :</p> <pre><code>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 </code></pre> <p>I tested it with several valid URLs, none passed the test, the request.GetResponse() always throws a WebException : "can not resolve distant name".</p> <p>What is wrong with this code ?</p> <p><strong>Update :</strong></p> <p>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)</p> <pre><code>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; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload