How to change user name in ASP.NET 2.0 Membership Provider

Profile.UserName is a readonly field. So, how do you change a user’s name? Many use email address as user name (like us, Pageflakes) and we want to allow users to change their email address which in turn changes their user name. So, how do you do it?

It looks like there’s no easy way to do it. You have to do the following:

  1. Create a new user using the new email address
  2. Get the password of the old account and set it to the new account. If you can’t get the old password via Membership provider, then ask user.
  3. Create a new profile for the new user account
  4. Copy all the properties from the old profile to the new profile object.
  5. Log out user from old account
  6. Auto sign in to the new account so that user does not notice what an incredible thing just happened.

Here’s how I do it:

if (Profile.UserName !=
newUserName)
{

// Changing email address of user.
Delete current user account and create

// a new one using the new email address
but the same password

if (
null !=
Membership.GetUser(newUserName))

throw
new
ApplicationException(
"There's another user with the same
email. Please enter a different email.");


MembershipUser newUser =
Membership.CreateUser(newUserName,
currentPassword);


// Create profile for the new user and
copy all values from current profile

// to new profile

ProfileCommon newProfile =
ProfileCommon.Create(newUserName,
true)
as
ProfileCommon;

    newProfile.IsInvited = Profile.IsInvited;
    newProfile.IsRealUser = Profile.IsRealUser;
    newProfile.Name = newUserName;

    newProfile.Save();


if (
Membership.ValidateUser(newUserName,
currentPassword))
    {

FormsAuthentication.SignOut();
        Session.Abandon();


// Delete the old profile and
user

ProfileManager.DeleteProfile(Profile.UserName);

Membership.DeleteUser(user.UserName);


//FormsAuthentication.SetAuthCookie(newUserName,
true);

FormsAuthentication.RedirectFromLoginPage(newUserName,

true);
    }
}
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

No related posts.

[If] anyone slays a human being-unless it be [in punishment] for murder or for spreading corruption on earth-it shall be as though he had slain all mankind; whereas, if anyone saves a life, it shall be as though he had saved the lives of all mankind... (Quran 5:32)

20 Comments

Leave a Reply

 

Get Adobe Flash playerPlugin by wpburn.com wordpress themes