Search code examples
c#asp.netmembership

How to set the current users email address in ASP.NET Membership?


im trying to set the current users email from within asp.net

Membership.GetUser().Email = txtEmail.Text;
Membership.UpdateUser(Membership.GetUser(User.Identity.Name));

but the next time i read the current users Email it has not changed

i read it like this

Membership.GetUser().Email

Solution

  • The method Membership.GetUser() returns a new user instance. Your first line is changing the Email property, and then proceeds by throwing away that change. Your second line will fetch the user again, with the old user, and update it.

    The documentation for Membership.UpdateUser contains an example of updating the email property. It all boils down to passing the same User instance from Membership.GetUser() to Membership.UpdateUser.

    // GetUser() without parameter returns the current logged in user.
    MembershipUser u = Membership.GetUser();       
    u.Email = email;    
    Membership.UpdateUser(u);
    

    This will cause issues if you have a custom MembershipProvider that uses the email field for identification purposes (and you login with email+password), then the user would still have User.Identity.Name equal to the old email until next login (or they get a new Forms-cookie).