views:

940

answers:

2

In ASP.Net, I am trying to get the UserId (i.e., the user GUID) of the user that just logged on, in the LoggedIn event of the Login control. That is, I want to grab the UserId before the user is moved to to the next page. This is the code I am using:

Protected Sub Login1_LoggedIn(ByVal sender As Object, _
  ByVal e As System.EventArgs) Handles Login1.LoggedIn

    Dim UserId As String
    UserId = Membership.GetUser.ProviderUserKey.ToString()

End Sub

However, I get an "Object reference not set to an instance of an object" error. This same code works well when I use it in subsequent pages, when a logged in user is accessing these pages.

+2  A: 

ScottGu has the answer to this problem, as explained in this blog post on the ASP.NET Forum:

The LoggedIn event fires immediately after the user is logged in with the login control -- but not before the next request to the site. As such, the User object isn't filled out yet.

If you change your code to something like:

Dim UserId As String
UserID = Membership.GetUser(Login1.UserName).ProviderUserKey.ToString()

It should work fine. Calling Membership.GetUser without passing the Username as a parameter will expect to grab the "current" logged in user. Of course, this fails for the above reasons as the User object is not yet populated. By passing the Login control's UserName property as a parameter to the GetUser() method, you explicitly force the Membership.GetUser method to retrieve the user as specified by name from the user store (i.e. database). This ensures that the Membership.GetUser method returns a valid MembershipUser object which allows you to access the ProviderUserKey property.

CraigTP
Tremendous - worked perfectly. Thanks for your help!
Proposition Joe
Thanks Craig, this worked perfectly for me as well.
John Fischer
A: 

I am trying the same thing, but my Login control (named Login1) is not being recognized in the LoggedIn handler. I get 'Name Login1 is not declared. I'm stumped.

Steve
If your Login control is nested in another control, you'll have to use FindControl("Login1") in the parent control. Another way to do this would me to cast `sender` to `Login`. I'm not sure of the VB syntax for casting, though.
Jim Schubert