Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET username change

Tags:

I have an asp.net site which uses the ASP.net Membership provider. Each comment, entry etc in the DB is tracked by the userID.

Since MS doesn't provide a way to change the username, I've found the userNAME in the "users" table in the DB and there is only 1 place where the username appears.

My question is,

Is it safe to provide an "edit profile" page where the user is allowed to edit their own username. Of course i would handle this change in the background by directly changing the "username" value in the DB.

Are there any downsides to this ? I've created and modified some test accounts and it seems to be fine, i am just wondering if there is any known negatives to this before putting it into production.

like image 611
Khalid Rahaman Avatar asked Aug 04 '09 20:08

Khalid Rahaman


Video Answer


1 Answers

cptScarlet's link was good, however I despise using stored procedures if I don't have to and I favor Entity Framework whenever possible. Here's what I did to change the user name, using EF 4.0 and .NET 4.0:

  1. Right click project -> Add New Item -> ADO.NET Entity Data Model
  2. Give it a proper name, I chose "MembershipModel.edmx" and click Add
  3. Select Generate from database and click Next
  4. Add the connection to your 'aspnetdb' database (the ASP.NET membership database)
  5. Give it a proper name, I chose "MembershipEntities"
  6. Click Next
  7. Drill into Tables and select aspnet_Users
  8. Change the Model Namespace to MembershipModel
  9. Click Finish

Now you can add code to create the EF object context and modify the database:

public void ChangeUserName(string currentUserName, string newUserName)
{
    using (var context = new MembershipEntities())
    {
        // Get the membership record from the database
        var currentUserNameLowered = currentUserName.ToLower();
        var membershipUser = context.aspnet_Users
            .Where(u => u.LoweredUserName == currentUserNameLowered)
            .FirstOrDefault();

        if (membershipUser != null)
        {
            // Ensure that the new user name is not already being used
            string newUserNameLowered = newUserName.ToLower();
            if (!context.aspnet_Users.Any(u => u.LoweredUserName == newUserNameLowered))
            {
                membershipUser.UserName = newUserName;
                membershipUser.LoweredUserName = newUserNameLowered;
                context.SaveChanges();
            }
        }
    }
}

Note: I did not account for application ID's in my code. I typically only ever have one application using the ASP.NET membership database, so if you have multiple apps, you'll need to account for that.

like image 111
Andrew Garrison Avatar answered Sep 20 '22 22:09

Andrew Garrison