Is it possible to change the username with the Membership API

后端 未结 7 2074
独厮守ぢ
独厮守ぢ 2020-12-03 13:38

I am using the default sql membership provider with ASP.NET and I would like to provide a page to change the user\'s username. I believe I am sure I could do this with a cus

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 14:06

    Here's a version that incorporates the Enterprise Libraries DAB and a couple other minor changes. Also, I don't see a point in returning a Boolean, since it's either going succeed or throw an exception.

            public static void ChangeUsername(string oldUsername, string newUsername)
        {
            if (string.IsNullOrWhiteSpace(oldUsername))
            {
                throw new ArgumentNullException("oldUsername cannot be null or empty");
            }
    
            if (string.IsNullOrWhiteSpace(newUsername))
            {
                throw new ArgumentNullException("newUsername cannot be null or empty");
            }
    
            if (oldUsername.Equals(newUsername))
            {
                return;
            }
    
            Database db = DatabaseFactory.CreateDatabase();
            using (DbCommand cmd = db.GetSqlStringCommand("UPDATE dbo.aspnet_Users SET UserName=@NewUsername, LoweredUserName=@LoweredNewUsername WHERE UserName=@OldUsername"))
            {
                db.AddInParameter(cmd, "@OldUsername", DbType.String, oldUsername);
                db.AddInParameter(cmd, "@NewUsername", DbType.String, newUsername);
                db.AddInParameter(cmd, "@LoweredNewUsername", DbType.String, newUsername.ToLower());
    
                db.ExecuteNonQuery(cmd);                
            }
        }
    

提交回复
热议问题