Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get UserID from ASP.Net Login control LoggedIn event

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.

like image 881
Proposition Joe Avatar asked Dec 17 '22 05:12

Proposition Joe


1 Answers

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.

like image 138
CraigTP Avatar answered Feb 28 '23 11:02

CraigTP