Update Dec 2017 Some good points have been raised in comments:
- Better have a separate field for new email while it is getting confirmed – in cases when user have entered incorrect email. Wait till the new email is confirmed, then make it the primary email. See very detailed answer from Chris_ below.
- Also there could be a case when account with that email already exist – make sure you check for that too, otherwise there can be trouble.
This is a very basic solution that does not cover all possible combinations, so use your judgment and make sure you read through the comments – very good points have been raised there.
// get user object from the storage
var user = await userManager.FindByIdAsync(userId);
// change username and email
user.Username = "NewUsername";
user.Email = "New@email.com";
// Persiste the changes
await userManager.UpdateAsync(user);
// generage email confirmation code
var emailConfirmationCode = await userManager.GenerateEmailConfirmationTokenAsync(user.Id);
// generate url for page where you can confirm the email
var callbackurl= "http://example.com/ConfirmEmail";
// append userId and confirmation code as parameters to the url
callbackurl += String.Format("?userId={0}&code={1}", user.Id, HttpUtility.UrlEncode(emailConfirmationCode));
var htmlContent = String.Format(
@"Thank you for updating your email. Please confirm the email by clicking this link:
<br><a href="https://stackoverflow.com/questions/25570025/{0}">Confirm new email</a>",
callbackurl);
// send email to the user with the confirmation link
await userManager.SendEmailAsync(user.Id, subject: "Email confirmation", body: htmlContent);
// then this is the action to confirm the email on the user
// link in the email should be pointing here
public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
var confirmResult = await userManager.ConfirmEmailAsync(userId, code);
return RedirectToAction("Index");
}