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.
ScottGu has the answer to this problem, as explained in this blog post on the ASP.NET Forum:
If you change your code to something like:
It should work fine. Calling
Membership.GetUserwithout passing the Username as a parameter will expect to grab the “current” logged in user. Of course, this fails for the above reasons as theUserobject is not yet populated. By passing theLogincontrol’sUserNameproperty as a parameter to theGetUser()method, you explicitly force theMembership.GetUsermethod to retrieve the user as specified by name from the user store (i.e. database). This ensures that theMembership.GetUsermethod returns a validMembershipUserobject which allows you to access theProviderUserKeyproperty.