Does anyone know how to enable a user to change username/email with ASP.NET identity with email confirmation? There\'s plenty of examples on how to change the password but I
Haven't looked at ChangeEmailOnIdentity2.0ASPNET yet, but couldn't you just take advantage of the fact that the UserName and Email values typically match? This allows you to change the Email column upon request and then UserName upon confirmation.
These two controllers seem to work for me:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task ChangeUserName(LoginViewModel model)
{
IdentityResult result = new IdentityResult();
try
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
SignInStatus verify = await SignInManager.PasswordSignInAsync(user.UserName, model.Password, false, false);
if (verify != SignInStatus.Success)
{
ModelState.AddModelError("Password", "Incorrect password.");
}
else
{
if (model.Email != user.Email)
{
user.Email = model.Email;
user.EmailConfirmed = false;
// Persist the changes
result = await UserManager.UpdateAsync(user);
if (result.Succeeded)
{
string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Confirm your updated email", "Please confirm your email address by clicking this");
return RedirectToAction("Index", new { Message = ManageMessageId.ChangeUserNamePending });
}
}
else
{
ModelState.AddModelError("Email", "Address specified matches current setting.");
}
}
}
}
catch (Exception ex)
{
result.Errors.Append(ex.Message);
}
AddErrors(result);
return View(model);
}
[AllowAnonymous]
public async Task ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var result = await UserManager.ConfirmEmailAsync(userId, code);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(userId);
if (user.Email != user.UserName)
{
// Set the message to the current values before changing
String message = $"Your email user name has been changed from {user.UserName} to {user.Email} now.";
user.UserName = user.Email;
result = await UserManager.UpdateAsync(user);
if (result.Succeeded)
{
ViewBag.Message = message;
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
}
else
{
result.Errors.Append("Could not modify your user name.");
AddErrors(result);
return View("Error");
}
}
return View("ConfirmEmail");
}
else
{
return View("Error");
}
}