Reputation:
I am using the following to control user log in authentication. This redirects fine when the user is inactive or locked out, but when the user is deleted from the database, I get an error message...
"Object reference not set to an instance of an object" on this line...
If currentuser IsNot Nothing And currentuser.IsApproved = False Or currentuser.IsLockedOut = True Then
What could be causing this to happen?
Protected Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
If User.Identity.IsAuthenticated Then
Dim currentuser As MembershipUser = Membership.GetUser()
If currentuser IsNot Nothing And currentuser.IsApproved = False Or currentuser.IsLockedOut = True Then
FormsAuthentication.SignOut()
FormsAuthentication.RedirectToLoginPage()
End If
If currentuser IsNot Nothing Then
Response.Redirect("~/media")
End If
End If
End Sub
Upvotes: 0
Views: 663
Reputation: 6159
Since 'And' receives precedence over 'Or' the expression will be evaluated as follows:
If
{
currentuser IsNot Nothing And currentuser.IsApproved = False //condition 1
Or
currentuser.IsLockedOut = True //condition 2
}
Then..
If current user is in fact nothing:
condition 1- will not fail, but condition 2 will throw
an exception since the code is trying to evaluate (nothing).somthing.
To fix the problem you'll have to add parentheses as shown:
If
currentuser IsNot Nothing //condition 1
And
(currentuser.IsApproved = False Or currentuser.IsLockedOut = True) //condition 2
Then..
Now, the 2nd condition will be evaluated only if the first condition is true.
Upvotes: 1
Reputation: 15893
Change the If
condition to:
If currentuser IsNot Nothing Then
If currentuser.IsApproved = False Or currentuser.IsLockedOut = True Then
FormsAuthentication.SignOut()
FormsAuthentication.RedirectToLoginPage()
End If
Response.Redirect("~/media")
End If
Upvotes: 1
Reputation: 460138
You need to parathesize the second part and use OrElse/AndAlso
, otherwise currentuser IsNot Nothing
will not be applied to all parts of your if
So this will fix it:
If currentuser IsNot Nothing AndAlso (Not currentuser.IsApproved OrElse currentuser.IsLockedOut) Then
Don't use Or
(and AND
) but OrElse
(and AndAlso
) which will short circuit. That means it will not evaluate the second part if the first part was already true
. Or
(and And
) on the other side will evaluate both parts always.
Upvotes: 1