Change username in MVC 5 [closed]
Asked Answered
R

3

9

I am using ASP.NET MVC5 and Identity 2.0 (beta).

It is possible for users to change the username?

I am trying using UserManager.UpdateAsync method throws an exception.

Regrads,

Fran.

Riedel answered 13/2, 2014 at 8:25 Comment(1)
What is the exception that is thrown?Burtie
S
12

Yes it is possible using the UpdateAsync method but you need to ensure that you update both the email and username fields.

var user = userManager.FindById(userId);
user.Email = email;
user.UserName = email;

var updateResult = await userManager.UpdateAsync(user);

This method works successfully for me

Scott answered 15/4, 2015 at 10:58 Comment(0)
C
3

This works for me:

 public async Task<ActionResult> ChangeUsername(string value)
        {
            if (UserManager.Users.Where(x => x.UserName == value).FirstOrDefault() == null) //chk for dupes
            {
                var user = UserManager.FindById(User.Identity.GetUserId());
                user.UserName = value;
                var updateResult = await UserManager.UpdateAsync(user);
                store.Context.SaveChanges();

                await SignInAsync(user,true);//user is cached until logout so do this to clear cache                
                return Content("true");
            }
            throw new HttpException(500, "Please select a different username");
        }
Caprice answered 24/7, 2015 at 5:44 Comment(0)
E
-5

Maybe it's not so beautiful, but try this:

db.Database.ExecuteSqlCommand("update AspNetUsers set UserName=" + NewUserName + " where UserName = " + OldUserName);
Estriol answered 20/3, 2014 at 5:50 Comment(2)
This is fragile as it depends on the database schema and connection directly. Much better to use the UserManger as suggested below.Burtie
Not to mention the risk of SQL injection!Strop

© 2022 - 2024 — McMap. All rights reserved.