Matrix001
Matrix001

Reputation: 1272

Problem with Membership.GetUser(User.Identity.Name);

I put the following algorithm into the login control event. It is fired after the user has logged in. A nuller point exception is thrown.

Answer is updated!! A new exception is thrown, it tells me that cast is not valid

   MembershipUser CurrentUser = Membership.GetUser(Login1.UserName,true);
        int i = (int)CurrentUser.ProviderUserKey;

I am assuming that this event is only fired if the user successfully logged in, and not failed.. should i use another event or objects. please help!!!

Upvotes: 1

Views: 4334

Answers (3)

leon
leon

Reputation: 772

You need to get the current user from the current HTTP Context. I believe the static instance you've passed to the GetUser method will not be populated with the users credentials.

Give this a try:

MembershipUser CurrentUser = Membership.GetUser(this.Context.User.Identity.Name);

Assuming your membership setup is working you should be able to retrieve the current user and if not, you need to handle the case that the user is not found- e.g by asking the user to login.

Upvotes: 1

Farzin Zaker
Farzin Zaker

Reputation: 3606

The code you have typed should work, but you can also use Parameter-less one

Membership.GetUser();

this helps you when user is logged in. but when no user is logged in User.Identity.Name is not correct. you can check with User.Identity.IsAuthenticated

in login page use this :

MembershipUser user = Membership.GetUser(Login1.UserName, true);

Upvotes: 1

danyolgiax
danyolgiax

Reputation: 13096

 protected void Login1_LoggedIn(object sender, EventArgs e)
    {
        MembershipUser user = Membership.GetUser(Login1.UserName, true);

then use

user.ProviderUserKey

Upvotes: 1

Related Questions