检查连接的用户的IP地址并与数据库进行比较

时间:2014-04-23 15:54:41

标签: asp.net vb.net

我正在尝试在登录时检查用户存储的IP地址,并与存储在数据库中的内容进行比较。 IP地址存储在默认aspnetdb的“注释”列中。

即使IP地址相同,每次用户连接时都会发送电子邮件。我只想在IP地址与存储的地址不同时发送电子邮件。

    Protected Sub LoginUser_LoggingIn(sender As Object, e As System.Web.UI.WebControls.LoginCancelEventArgs) Handles LoginUser.LoggingIn

    Dim CurrentUser As MembershipUser = Membership.GetUser(LoginUser.UserName)

    If (CurrentUser IsNot Nothing) Then

        Dim IPAddress As String = HttpContext.Current.Request.UserHostAddress

        Dim CurrentIP As String = CurrentUser.Comment

        If (IPAddress IsNot CurrentIP) Then

            Dim IP_Change As New Thread(
                Sub()
                    Dim mailObject As New System.Net.Mail.MailMessage()
                    Dim emailCredentials As New System.Net.NetworkCredential("my@domain.com", "password")

                    mailObject.Subject = "User " & CurrentUser.ToString & " is connecting from a new IP Address ( " & IPAddress & " )"
                    mailObject.Body = "User is connecting from a new IP Address"

                    mailObject.To.Add("my@email.com")
                    mailObject.From = New System.Net.Mail.MailAddress("my@domain.com")
                    mailObject.IsBodyHtml = True

                    Dim SmtpMail As New System.Net.Mail.SmtpClient("my.domain.com")
                    SmtpMail.UseDefaultCredentials = False
                    SmtpMail.EnableSsl = False
                    SmtpMail.Credentials = emailCredentials
                    SmtpMail.Port = 587
                    SmtpMail.Send(mailObject)
                End Sub
            )
            IP_Change.Start()

            CurrentUser.Comment = IPAddress
            Membership.UpdateUser(CurrentUser)

        End If

    End If

End Sub

1 个答案:

答案 0 :(得分:2)

由于参考比较,您似乎与IsNot的行为不一致。

将您的比较更改为以下内容:If (IPAddress <> CurrentIP) Then,它应该有效。