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:
- Create a new user using the new email address
- 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.
- Create a new profile for the new user account
- Copy all the properties from the old profile to the new profile
object.
- Log out user from old account
- 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);
}
}