VB.NET HTTPWEBRESPONSE WebException解决方法

时间:2012-04-15 23:47:57

标签: vb.net httpwebresponse

我正在尝试使用文件创建一个简单的登录系统

Dim response As System.Net.HttpWebResponse = request.GetResponse()
        If response.StatusCode = HttpStatusCode.NotFound Then
        MsgBox("Invalid Login")
Else

My Code Here

但是当我调试它并测试它时,它仍然给我404错误。而不是弹出窗口。

还有其他方法吗?

编辑:

这是我的代码

        Try
        Dim response As HttpWebResponse = request.GetResponse()

        MessageBox.Show("Allgood")
    Catch ex As WebException
        If response.StatusCode = HttpStatusCode.NotFound Then
            MsgBox("Invalid Login")
        End If
               End Try
    Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
    Dim passcheck As String = sr.ReadToEnd
    Dim pass As String = PasswordTextBox.Text
    If passcheck.Contains(pass) Then
        MessageBox.Show("Welcome " + UsernameTextBox.Text)
        Form1.Show()
        Me.Close()
    Else
        MessageBox.Show("Invalid Login")

    End If

End Sub

2 个答案:

答案 0 :(得分:1)

我相信它会抛出WebException,因此您需要将GetResponse包装在Try Catch块中并捕获Web异常,然后显示您自己的对话框。

Dim response As System.Net.HttpWebResponse
Try
    response = request.GetResponse()

    'If it gets here, it did not throw an exception
    MessageBox.Show("It's all good.")
Catch ex as WebException
    If DirectCast(ex.Response, System.Net.HttpWebResponse).StatusCode  = HttpStatusCode.NotFound Then
        MsgBox("Invalid Login")
    End If
End Try

答案 1 :(得分:0)

很奇怪,请确保您的应用程序是项目属性中的 Windows窗体应用程序。但是,作为解决方法,您可以使用下一个代码在Visual Studio输出窗口中打印它。

Debug.WriteLine("Invalid Login")

要启用“输出窗口”,请转到菜单“查看”,然后选择“输出”或按 Ctrl + W + O