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);
    }                    
}
Published Fri, Aug 18 2006 5:02 by omar
Filed under:

Comments

# Why use ASP.NET 2.0 Membership Provider?

Friday, August 18, 2006 11:37 AM by Dennis Gorelik
Omar, why do you use profiles (vs designing your own user database structure for keeping users' info)?

What does it give to you?
Speed of development?
Optimized permormance?
Ease of maintanence?
Anything else?

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

Sunday, August 20, 2006 1:05 PM by Norm Petroff - ASP.NET Programmer
That works... but what if your program is tracking user's actions by their user ID? I have an application that keeps a history of every change made by a user to the database. What I need to do is to change the username and email but keep the same userID.  

So far the only thing I've been able to come up with is to connect to the membership database (ADO) and change the username in the "User" table but keep the UserID intact.

It's a pain to do it this way.  Microsoft shouldn't have made the username readonly.

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

Sunday, August 20, 2006 3:00 PM by Norm Petroff - ASP.NET Programmer
Here is some sample code to make the change.

Dim UserNameOld As String = txtUserName.Text
Dim UserNameNew As String = txtEmail.Text.ToLower

'Create a membership object for the user being edited. This will give direct access to the user's membership information so it can be updated.
Dim myUser As MembershipUser = Membership.GetAllUsers.Item(UserNameOld)

'Create an object for the user being edited so we can gain access to that user's profile information and update it.
       Dim myProfile As ProfileCommon = ProfileBase.Create(UserNameOld)

'Update the Email Address.
myUser.user = UserNameNew

'Update the username. ASP.NET Membership does not have a method to change the username (it's read only for security). The only way to change it is to manually connect to the "aspnet_Users" table using ADO and do an update.
       Dim myConnection As New SqlConnection
       Dim myCommand As New SqlCommand
       Dim myReader As SqlDataReader

       myConnection.ConnectionString = ConfigurationManager.ConnectionStrings("BedRegistry").ConnectionString

       myCommand.CommandText = ("UPDATE aspnet_Users SET UserName = '" & UserNameNew & "' , LoweredUserName = '" & UserNameNew & "' WHERE (UserName = '" & myUser.UserName & "') ")
       myCommand.CommandType = CommandType.Text
       myCommand.Connection = myConnection
       myCommand.Connection.Open()

       myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)

       myConnection.Dispose()
       myCommand.Dispose()
       myCommand.Dispose()

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

Sunday, August 20, 2006 3:03 PM by Norm Petroff - ASP.NET Programmer
Sorry.. there was a bug there...

'update Email should be.
myUser.Email = UserNameNew

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

Tuesday, August 22, 2006 11:27 AM by Jenny
I end up with duplicate users and profiles though?  Seems as soon as I sign in the new user - the old one appears back in the database

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

Wednesday, August 23, 2006 2:53 AM by Darren
Just write some SQL or a sproc to change the username in the aspnet_Users table of the membership database no?

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

Wednesday, August 23, 2006 2:54 AM by Darren
Oops. Someone already said that

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

Wednesday, August 23, 2006 6:55 PM by Mark
I wrote a sproc to update the aspnet_User table and I get duplicate users and profiles after the update.  There must be a better way to do this.

Also, the SQL suggested does not check to see if the new Username already exists.  Usernames must be unique.

Does anyone have a solution that is actually in use?

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

Thursday, September 07, 2006 1:40 AM by Tim@velocitysc
Why not just do: Create new: Membership.CreateUser(Guid.NewGuid(), PasswordText) To login: Membership.ValidateUser(Membership.GetUserNameByEmail(EmailText), PasswordText) And whenever they update their email: Membership.GetUser().Email = "newemail@domain.com" ...the login still works, and anything associated to the username and providerkey remain associated without having to delete and create new accounts, etc.

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

Thursday, September 07, 2006 3:19 AM by omar

The solution I have shown here is already in use at Pageflakes. So, you can trust that it works well.

Tim, we want to change the user name and let the regular login process work as it does.

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

Thursday, September 07, 2006 2:29 PM by Tim@velocitysc
Ok, guess I don't know the full requirements. But this method also let's you us the regular login process. Just have to wire up the athenticate event, Login1_Authenticate, and just set e.Authenticated = Membership.GetUserNameByEmail(EmailText), PasswordText). We have used this in several areas with success also.

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

Tuesday, February 06, 2007 10:04 AM by Thomas

I use the following query to update the username:

UPDATE    aspnet_Users

SET              UserName = @NewUserName, LoweredUserName = @NewLoweredUserName

WHERE     (ApplicationId = @Original_ApplicationId) AND (LoweredUserName = @Original_LoweredUserName)

Works almost fine. It does update the username, but it also creates a new entry in aspnet_Users with the old username. It doesn't create anything in the aspnet_membership. I don't want to create a new user and copy the old values since I reference the UserId. Any ideas why it creates a new entry with the old username?

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

Tuesday, February 06, 2007 11:10 AM by omar

ASP.NET Issues a cookie with the user name. So, next time when a request hits with the specified cookie, ASP.NET creates a row in aspnet_users table.

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

Tuesday, February 06, 2007 2:49 PM by Thomas

Is there any way to prevent this?

TIA

Thomas

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

Tuesday, February 06, 2007 3:12 PM by Thomas

I think I solved it by looking at some of your code at the top.

Immediately after updating the username, I log the user out and in again:

FormsAuthentication.SignOut();                       HttpContext.Current.Session.Abandon();                       FormsAuthentication.SetAuthCookie(newUserName, true);

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

Monday, February 12, 2007 8:10 AM by Thomas

Hm.. that didn't do it afterall. How do I delete the ASP.Net cookie for the old username?

TIA

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

Thursday, February 15, 2007 10:15 AM by Thomas

Now I solved it! I had to create a ProfileCommon with the new username to prevent a row to be inserted with the old username

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

Tuesday, February 20, 2007 11:33 AM by Will

This is clearly a messy way of doing things - and also bad because you've changed the UserId Guid/uniqueidentifier. So if you have any custom personalization or other references in your code (or even in your URLs) to this Guid you have to also manually update all those references.

You're much better off manually editing the aspnet_Membership / aspnet_Users tables, as others have noted.

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

Monday, February 26, 2007 5:15 AM by germane

Hi,

does anyone have a working sample code for updating the UserName without changing the UserId ??

I guess a challenge here is to allow users to change their username (which is also their email address) and keep them signed in.

Please post your sample code if you have it.

Thanks,

germane.

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

Monday, February 26, 2007 7:50 AM by Thomas

This works for me:

   private static object changeUserNameLock = new object();

   /// <summary>

   /// Change username

   /// </summary>

   /// <param name="userID">ID of user</param>

   /// <param name="newUserName">New username</param>

   /// <returns>If successful</returns>

   public static bool ChangeUserName(Guid userID, string newUserName)

   {

       lock (changeUserNameLock)

       {

           bool succes = false;

           newUserName = newUserName.Trim();

           ///Make sure there is no user with the new username

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

           {

               MembershipUser u = Membership.GetUser(userID);

               string oldUsername = u.UserName;

               //get current application

               UsersDataSetTableAdapters.aspnet_ApplicationsTableAdapter appsTA = new UsersDataSetTableAdapters.aspnet_ApplicationsTableAdapter();

               UsersDataSet.aspnet_ApplicationsDataTable apps = appsTA.GetDataByApplicationName(Membership.ApplicationName);

               if (apps.Count > 0)

               {

                   UsersDataSet.aspnet_ApplicationsRow app = apps[0];

                   //change username

                   UsersDataSetTableAdapters.aspnet_UsersTableAdapter usersTA = new UsersDataSetTableAdapters.aspnet_UsersTableAdapter();

                   int result = usersTA.UpdateUserName(newUserName, newUserName.ToLower(), app.ApplicationId, u.UserName.ToLower());

                   //if update was succesful

                   if (result > 0)

                   {

                       ProfileCommon profile = (ProfileCommon)ProfileCommon.Create(newUserName, true);

                       //ASP.NET Issues a cookie with the user name. So, next time when a request hits with the specified cookie, ASP.NET creates a row in aspnet_users table.

                       //To prevent this we first sign the user out and then sign him/her in again

                       //http://msmvps.com/blogs/omar/archive/2006/08/18/108003.aspx

                       string cookieName = FormsAuthentication.FormsCookieName;

                       HttpCookie authCookie = HttpContext.Current.Request.Cookies[cookieName];

                       FormsAuthenticationTicket authTicket = null;

                       try

                       {

                           authTicket = FormsAuthentication.Decrypt(authCookie.Value);

                           FormsIdentity fi = new FormsIdentity(new FormsAuthenticationTicket(authTicket.Version, newUserName, authTicket.IssueDate, authTicket.Expiration, authTicket.IsPersistent, authTicket.UserData));

                           string y = HttpContext.Current.User.Identity.Name;

                           string[] roles = authTicket.UserData.Split(new char[] { '|' });

                           System.Security.Principal.GenericPrincipal gi = new System.Security.Principal.GenericPrincipal(fi, roles);

                           HttpContext.Current.User = gi;

                       }

                       catch (Exception ex)

                       { //Log exception details (omitted)

                       }

                       FormsAuthentication.SignOut();

                       HttpContext.Current.Session.Abandon();

                       FormsAuthentication.SetAuthCookie(newUserName, false);

                       succes = true;

                   }

               }

           }

           return succes;

       }

   }

In my dataset I have a method called UpdateUsername:

UPDATE    aspnet_Users

SET              UserName = @NewUserName, LoweredUserName = @NewLoweredUserName

WHERE     (ApplicationId = @Original_ApplicationId) AND (LoweredUserName = @Original_LoweredUserName)

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

Wednesday, April 25, 2007 6:35 AM by Namwar Rizvi
Hi Guys, I have created the following stored procedure which can easily change the old Login Name to New LoginName. I have tested it and it is running perfectly fine. It is in SQL Server 2005 TSQL format. NOTE: Before executing, replace tblUsers and its respective columns with your own User Table. Following is the code: Create Procedure uspUsers_ChangeLoginName @p_OldName varchar(20),@p_NewName varchar(20) as Begin Set Nocount On BEGIN TRY --Check if old user exists if exists(Select Login from tblUsers where Lower(Login)=Lower(@p_OldName)) Begin Begin Transaction Update tblUsers set Login=@p_NewName where Login=@p_OldName Update aspnet_Users Set UserName=@p_NewName, LoweredUserName=Lower(@p_NewName) Where LoweredUserName=Lower(@p_OldName) Commit Transaction Print @p_OldName + ' has been successfuly changed to ' + @p_NewName End Else Begin Print 'Error: Old User Name "'+@p_OldName + '" does not exist. Cannot change the User Name.' End END TRY BEGIN CATCH --Rollback any tranction, if it was started If @@Trancount > 0 Rollback Transaction Print 'Error occured while trying to replace old UserName to New UserName:'+char(10) Print 'Error No:' + Convert(varchar,ERROR_NUMBER())+char(10) Print 'Error Line:' + Convert(varchar,ERROR_LINE())+char(10) Print 'Error Message:' + Convert(varchar,ERROR_MESSAGE()) END CATCH; End

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

Friday, May 04, 2007 12:42 PM by Cesar Vega

In the first comment someone raised an interesting question, and I'm still searching for that answer.

Is it just to save some development time? Or are there any other super-cool reasons to use the built-in membership provider?

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

Saturday, May 05, 2007 11:45 PM by omar

I use ASP.NET 2.0 Membership and Profile Provider because:

1) It helps me get started pretty quick

2) I eventually end up creating similar type of tables and SPs for user, role, profile etc. So, no point making my own

3) Whether I use ASP.NET Profile or my own implementation, I always have to tweak things around for performance, scalability, bugs etc. So, whether I use my own implementation or use ASP.NET's solution, eventually it ends up in similar maintenance effort. But ASP.NET Membership/Profile at least helps me get started very quickly.

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

Monday, May 21, 2007 5:57 AM by Adonis

interesting

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

Monday, May 21, 2007 10:50 AM by Costas

Interesting...

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

Monday, May 21, 2007 1:03 PM by Haris

Hi Omar,

i want to create new login control (becouse this one from microsoft create tables and i want to use divs and litle more html code) but o want to use also ASP.NET 2.0 Membership and Profile Provider. So i need to login user in memebrship provider and i don't know where do I do that.

The reason why i want this also is becouse i  have used on many places isAuthenticated, and other stuff from Membership provider.

Thnx in advance,

haris

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

Tuesday, May 22, 2007 8:39 PM by Athanassios

interesting

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

Wednesday, May 23, 2007 1:27 AM by Loukas

Interesting...

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

Wednesday, May 23, 2007 3:26 AM by Leandros

interesting

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

Friday, May 25, 2007 5:24 PM by Jollymugs

Hey Thomas, cheers for that code. I works perfectly. Thanks ;)

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

Tuesday, June 05, 2007 2:17 PM by Giannis

Interesting...

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

Wednesday, June 13, 2007 3:22 PM by Joanne

Hi all,

I need to do this for an upcoming project as well, and my first thought was to use a GUID for the UserName, exactly as Tim outlined above.  Has anyone else tried this approach?  Any hidden problems with it?  It seems by far the most straight-forward.

Thx,

Joanne

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

Wednesday, June 20, 2007 11:02 AM by Steven Provecher

I am facing the same issue. A legacy application using the email address as the username. I an thinking:

On Import of User to the Membership generate a Unique username for use in Membership. When a user logs in lookup the username in a non-membership table and pass that to the Membership along with the password to log the user in. The user can change email address anytime and knows nothing about the Membership username.

Does this make Sense?

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

Friday, June 22, 2007 7:37 PM by Marko

Interesting...

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

Monday, June 25, 2007 9:05 AM by Platon

interesting

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

Monday, June 25, 2007 3:40 PM by Kristion

Interesting...

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

Tuesday, June 26, 2007 4:13 AM by Eleni

Interesting...

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

Friday, July 13, 2007 11:53 AM by Socrates

Interesting...

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

Saturday, July 14, 2007 1:56 AM by Nektarios

interesting

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

Saturday, July 14, 2007 10:20 AM by Yiannis

Interesting...

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

Saturday, July 14, 2007 10:30 AM by Dion

Interesting...

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

Monday, July 16, 2007 1:28 PM by Spiridon

interesting

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

Wednesday, July 18, 2007 7:51 AM by Chrysostomos

Interesting...

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

Wednesday, July 18, 2007 10:08 AM by Dighenis

Interesting...

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

Thursday, July 19, 2007 7:11 AM by Panagiotis

interesting

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

Thursday, July 19, 2007 7:08 PM by Paulos

Interesting...

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

Sunday, July 22, 2007 1:26 AM by Orion

interesting

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

Tuesday, July 24, 2007 2:41 AM by Adonis

interesting

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

Saturday, July 28, 2007 11:04 AM by Silvanos

interesting

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

Monday, July 30, 2007 3:48 AM by Demetri

Interesting...

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

Wednesday, August 01, 2007 9:05 AM by Kosmas

interesting

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

Thursday, August 02, 2007 1:14 AM by Zeus

Interesting...

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

Sunday, August 05, 2007 11:42 PM by Vilyamsg

Hello! great idea of color of this siyte!

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

Wednesday, September 12, 2007 10:39 AM by Daniel Farrow

If all you need to do is use an email address as a "UserName", wouldn't it be better to simply create a guid for UserName when the account is created and then never change it?  The user can log in by entering e-mail address and the code can use that to pull up the UserName whenever it is needed.  This avoids messy issues with keeping the e-mail address in synch with UserName, in case the user's email changes.

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

Tuesday, September 25, 2007 8:59 AM by Jon Swain

I ended up just going straight to the database level and changing each username within the database.  You can easily do this in the aspnet_users table.

See:

jonswain.wordpress.com/.../renamingchanging-username-in-aspnet

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

Tuesday, October 02, 2007 2:37 AM by Ben Erwood

Daniel,

I've used the approached you describe and it has worked just fine for me.

Cheers, Ben

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

Saturday, October 20, 2007 5:28 AM by boby

i usee the query in this controlchange password

"select password into register where

email='"+changepassword1.Username+"'"

then

it give massege for falier

if i use username field in username text the give success massege

but i want to control on email basies

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

Tuesday, October 30, 2007 1:29 PM by Doug Taylor

After reading the discussion above I created the following stored procedure that seems to do the trick.  Sorry if it got word-wrapped, but hopefully you get the idea.  I'm surprised that Microsoft would have the foresight to distinguish between UserId and UserName, but not build in the ability to change the username.  Why else would you have a seperate UserId value if not to let UserName change?

Working on something now that'll allow this to be called in code along the lines of:

Membership.ChangeUserName("OldName", "NewName")

Hope it helps!

------------

CREATE PROCEDURE dbo.aspnet_Membership_ChangeUserName

@ApplicationName NVARCHAR(256),

@OldUserName NVARCHAR(256),

@NewUserName NVARCHAR(256)

AS

BEGIN

DECLARE @UserId AS UNIQUEIDENTIFIER

DECLARE @ApplicationId AS UNIQUEIDENTIFIER

-- Lookup the ApplicationId

SELECT @ApplicationId = ApplicationId

FROM dbo.aspnet_Applications

WHERE LoweredApplicationName = LOWER(@ApplicationName)

-- Lookup the UserId

SELECT @UserId = UserId

FROM aspnet_Users

WHERE ApplicationId = @ApplicationId AND LoweredUserName = LOWER(@OldUserName)

-- Change the username

UPDATE dbo.aspnet_Users

SET UserName = @NewUserName, LoweredUserName = LOWER(@NewUserName)

WHERE ApplicationId = @ApplicationId AND UserId = @UserId

END

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

Tuesday, October 30, 2007 2:40 PM by Doug Taylor

Here's a class that interfaces with the stored procedure I just mentioned.  It inherits from System.Web.Security.MembershipUser, and I use it like this (VB.NET):

Dim myUser As cMembershipUser

myUser = Membership.GetUser(Me.OriginalUserName)

myUser.ChangeUserName("NewUserNameHere")

--------------------------

Imports Microsoft.VisualBasic

Imports System.Data.SqlClient

Public Class cMembershipUser

   Inherits System.Web.Security.MembershipUser

   Public Function ChangeUserName(ByVal NewUserName As String) As Boolean

       Dim IsSuccsessful As Boolean = False

       If IsUserNameValid(NewUserName) Then

           Dim myConn As New SqlConnection(ConfigurationManager.ConnectionStrings("pbv2005").ToString)

           Dim cmdChangeUserName As New SqlCommand()

           With cmdChangeUserName

               .CommandText = "dbo.aspnet_Membership_ChangeUserName"

               .CommandType = Data.CommandType.StoredProcedure

               .Connection = myConn

               .Parameters.Add("@ApplicationName", Data.SqlDbType.NVarChar)

               .Parameters.Add("@OldUserName", Data.SqlDbType.NVarChar)

               .Parameters.Add("@NewUserName", Data.SqlDbType.NVarChar)

           End With

           cmdChangeUserName.Parameters("@ApplicationName").Value = ConfigurationManager.AppSettings("AppKey").ToString

           cmdChangeUserName.Parameters("@OldUserName").Value = Me.UserName

           cmdChangeUserName.Parameters("@NewUserName").Value = NewUserName

           Try

               myConn.Open()

               cmdChangeUserName.ExecuteNonQuery()

               myConn.Close()

               IsSuccsessful = True

           Catch ex As Exception

               IsSuccsessful = False

           End Try

       Else

           IsSuccsessful = False

       End If

       Return IsSuccsessful

   End Function

   Private Function IsUserNameValid(ByVal username As String) As Boolean

       ' Add whatever username requirement validation you want here, doesn't

       ' the membership provider have some build in functionality for this?

       If username.Length > 4 Then

           Return True

       Else

           Return False

       End If

   End Function

End Class

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

Thursday, November 01, 2007 10:23 PM by Doug Taylor

Hey folks, looks like I spoke too soon... a problem with my class above is Membership.GetUser() is designed to return a MembershipUser object.  So when I try to do this:

Dim myUser As cMembershipUser

myUser = Membership.GetUser(Me.OriginalUserName)

it fails because myUser is the wrong type, and even when I try to cast the return result it doesn't work.  Anyone know how to use inheretance, but still let your modified class be used in this way?  In the meantime as a workaround I created a static utility class with a method that lets me update the username interfacing with the stored procedure above.  I've pasted it below, and you'd use it like this:

utils.ChangeUserName("oldUserName", "newUserName")

----------------

Imports Microsoft.VisualBasic

Imports System.Data.SqlClient

Public Class utils

   Public Shared Function ChangeUserName(ByVal oldUserName As String, ByVal newUserName As String) As Boolean

       Dim IsSuccsessful As Boolean = False

       If IsUserNameValid(NewUserName) Then

           Dim myConn As New SqlConnection(ConfigurationManager.ConnectionStrings("pbv2005").ToString)

           Dim cmdChangeUserName As New SqlCommand()

           With cmdChangeUserName

               .CommandText = "dbo.aspnet_Membership_ChangeUserName"

               .CommandType = Data.CommandType.StoredProcedure

               .Connection = myConn

               .Parameters.Add("@ApplicationName", Data.SqlDbType.NVarChar)

               .Parameters.Add("@OldUserName", Data.SqlDbType.NVarChar)

               .Parameters.Add("@NewUserName", Data.SqlDbType.NVarChar)

           End With

           cmdChangeUserName.Parameters("@ApplicationName").Value = ConfigurationManager.AppSettings("AppKey").ToString

           cmdChangeUserName.Parameters("@OldUserName").Value = oldUserName

           cmdChangeUserName.Parameters("@NewUserName").Value = newUserName

           Try

               myConn.Open()

               cmdChangeUserName.ExecuteNonQuery()

               myConn.Close()

               IsSuccsessful = True

           Catch ex As Exception

               IsSuccsessful = False

           End Try

       Else

           IsSuccsessful = False

       End If

       Return IsSuccsessful

   End Function

   Private Shared Function IsUserNameValid(ByVal username As String) As Boolean

       ' Add whatever username requirement validation you want here, doesn't

       ' the membership provider have some build in functionality for this?

       If username.Length > 4 Then

           Return True

       Else

           Return False

       End If

   End Function

End Class

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

Thursday, November 01, 2007 10:43 PM by FM

Works like a charm Doug!  Thanks.  I added the following to your stored procedure cause I'm anal and I want everything to be consistent:

-- Change the e-mail address

UPDATE dbo.aspnet_Membership

SET Email = @NewUserName, LoweredEmail = LOWER(@NewUserName)

WHERE ApplicationId = @ApplicationId AND UserId = @UserId

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

Saturday, November 03, 2007 9:54 PM by Doug Taylor

Like the addition, but I'm guessing you do this because your front end has the user log in with their e-mail address and password: making the e-mail behave as if it was the username.  For those of us still using the "out of the box" behavior, this isn't the case, so you you wouldn't necessarily want to overwrite the e-mail address with a username change.

However I wonder if that's a better way to go... probably easier for users to remember an e-mail address over a username, especially if they visit the site sporadically.

# Membership Provider: changing the username

Sunday, November 04, 2007 10:12 PM by Powered by Vision

Membership Provider: changing the username

# Where's the ChangeUserName() function?

Tuesday, November 13, 2007 3:59 PM by Code Journal .NET

Where's the ChangeUserName() function?

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

Wednesday, November 14, 2007 8:06 PM by Alexyqf

<a href=  ></a>

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

Wednesday, November 14, 2007 8:06 PM by Alexwvg

<a href=  ></a>

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

Wednesday, November 14, 2007 8:06 PM by Alexqgr

<a href=  ></a>

# Where is the ChangeUserName() function?

Thursday, November 15, 2007 11:21 AM by Dev by Doug

I recently built a site that uses the Microsoft ASP.NET Membership, Role and Profile providers (2.0 framework

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

Thursday, January 10, 2008 4:49 PM by sweetpea-hk

<a href= http://gener4.com >golden valley cabin rentals</a>

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

Sunday, September 28, 2008 6:23 AM by codebounce.com

Hellons!

I stumbled upon this and thought was very useful. My only concern as someone already pointed out: updating all references to the old id.

In spite of this, still useful.

I also bookmarked it:

www.codebounce.com/ASPNET

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

Thursday, December 11, 2008 10:40 AM by muadib

Thanks to Omar, Doug Taylor and Thomas

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

Friday, February 20, 2009 3:50 AM by D-Ball

Thomas, your code works great.  Thanks!

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

Friday, February 20, 2009 3:58 AM by D-Ball

Here is the VB version of Thomas' code...

1. Make sure New UserName is Unique

2. Update the aspnet_Users table directly

3. Execute to following code to change the username/cookie/identity without leaving the webpage...

' Obtains the name of the FormsAuthentication Cookie, uses that name to request the Cookie and Decrypts the Cookies information into a AuthTicket

Dim AuthTicket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(HttpContext.Current.Request.Cookies(FormsAuthentication.FormsCookieName).Value)

' Instantiates a new user identity authenticated using forms authentication based on the FormsAuthenticationTicket.

' The FormsAuthenticationTicket has been created using the exact same parameters of the user with the Old Username except the Old Username has been updated with the New Username.

Dim NewFormsIdentity As New FormsIdentity(New FormsAuthenticationTicket(AuthTicket.Version, NewUsername, AuthTicket.IssueDate, AuthTicket.Expiration, AuthTicket.IsPersistent, AuthTicket.UserData))

' Parse out the AuthTicket's UserData into a string array of Roles

Dim Roles As String() = AuthTicket.UserData.Split("|".ToCharArray)

' Creates a new user that has the NewFormsIdentity and belongs to the array of Roles, if any, that was stored in the FormsAuthenticationTicket

Dim NewGenericPrincipal As New System.Security.Principal.GenericPrincipal(NewFormsIdentity, Roles)

' Sets the security information for the current HTTP request to the new user.  The Username has now been changed (i.e. HttpContext.Current.User.Identity.Name = NewUsername, prior to this step is was the OldUsername)

HttpContext.Current.User = NewGenericPrincipal

' Removes the forms-authentication ticket from the browser

FormsAuthentication.SignOut()

' Cancels the current session

HttpContext.Current.Session.Abandon()

' Creates an authentication ticket for the supplied New Username and adds it to the cookies collection of the response or the URL

FormsAuthentication.SetAuthCookie(HttpContext.Current.User.Identity.Name, AuthTicket.IsPersistent)

4. Response.Redirect back to the same page if needed.

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

Wednesday, August 19, 2009 8:50 AM by Marwan Roushdy

Here is a C# version of Doug's plus corrected some issues regarding finding the username because sometimes it could not be available in web.config.

///////////////////////

public class utils

   {

       public static bool ChangeUserName(string oldUserName,string newUserName)

       {

           bool IsSuccsessful = false;

           string ApplicationName;

           if(IsUserNameValid(newUserName))

           {

               if ((ConfigurationManager.ConnectionStrings["applicationName"] == null) || String.IsNullOrEmpty(ConfigurationManager.ConnectionStrings["applicationName"].ToString()))

               {ApplicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;}

               else

               { ApplicationName = ConfigurationManager.ConnectionStrings["applicationName"].ToString(); }

               SqlConnection myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());

              SqlCommand cmdChangeUserName= new SqlCommand();

              cmdChangeUserName.CommandText="dbo.aspnet_Membership_ChangeUserName";

              cmdChangeUserName.CommandType = CommandType.StoredProcedure;

              cmdChangeUserName.Connection = myConn;

              cmdChangeUserName.Parameters.Add("@ApplicationName", SqlDbType.NVarChar);

              cmdChangeUserName.Parameters.Add("@OldUserName", SqlDbType.NVarChar);

              cmdChangeUserName.Parameters.Add("@NewUserName", SqlDbType.NVarChar);

              cmdChangeUserName.Parameters["@ApplicationName"].Value = ApplicationName;

              cmdChangeUserName.Parameters["@OldUserName"].Value = oldUserName;

              cmdChangeUserName.Parameters["@NewUserName"].Value = newUserName;

               try

               {

              myConn.Open();

              cmdChangeUserName.ExecuteNonQuery();

              myConn.Close();

              IsSuccsessful = true;

              }

               catch(Exception ex )

               {IsSuccsessful = false;}

           }

           else{IsSuccsessful = false;}

           return IsSuccsessful;

       }

       private static bool IsUserNameValid(string username)

       {

         //Add whatever username requirement validation you want here, doesnt

         //the membership provider have some build in functionality for this?

          return true;

       }

   }

Leave a Comment

(required) 
(required) 
(optional)
(required)