asp.net - .NET 身份电子邮件/用户名更改

标签 asp.net asp.net-identity

有谁知道如何让用户通过电子邮件确认来更改具有 ASP.NET 身份的用户名/电子邮件?有很多关于如何更改密码的示例,但我找不到任何相关内容。

最佳答案

2017 年 12 月更新评论中提出了一些好的观点:

  • 在确认新电子邮件时,最好有一个单独的字段 - 以防用户输入不正确的电子邮件。等到新电子邮件得到确认后,将其设为主要电子邮件。请参阅下面 Chris_ 的非常详细的回答。
  • 此外,可能存在使用该电子邮件地址的帐户已存在的情况 - 请务必检查该帐户,否则可能会出现问题。

这是一个非常基本的解决方案,并不涵盖所有可能的组合,因此请运用您的判断并确保阅读评论 - 那里提出了非常好的观点。

// 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='{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");
}

关于asp.net - .NET 身份电子邮件/用户名更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25570025/

相关文章:

c# - 使用 Asp.Net 5 Identity 3.0 注销后未删除 Cookie

c# - 将服务器端 onclick 事件添加到以编程方式创建的 div

jquery - 如何从node.js服务器的asp.net api Restful Web服务获取数据?

asp.net - ASP.Net 中的 session 模式?

c# - 在页面加载时检查用户身份验证

c# - 避免在 asp.net 中的按钮单击事件期间刷新页面

c# - 身份框架为用户创建一个新密码(没有密码)

c# - ASP.Net Core 2.1 IdentityCore(用户登录时未添加角色声明)

windows - 我可以将 Windows 身份验证与 ASP.Net Identity 一起使用吗?

c# - 将 'hd' 参数附加到 redirectUrl ASP.NET Core 1 with Identity 3