添加邮箱激活功能,使用户能主动激活邮箱:
    image.png

    添加 ViewModel:

    1. public class EmailAddressViewModel
    2. {
    3. [Required]
    4. [EmailAddress]
    5. public string Email { get; set; }
    6. }

    修改 AccountController,添加激活邮箱相关的逻辑:

    1. #region 激活邮箱
    2. [HttpGet]
    3. public IActionResult ActivateUserEmail()
    4. {
    5. return View();
    6. }
    7. [HttpPost]
    8. public async Task<IActionResult> ActivateUserEmail(EmailAddressViewModel model)
    9. {
    10. if (ModelState.IsValid)
    11. {
    12. var user = await _userManager.FindByEmailAsync(model.Email);
    13. // 当前已经存在老用户时 1.生成电子令牌 2.以及电子令牌确认URL
    14. if (user != null)
    15. {
    16. if (!await _userManager.IsEmailConfirmedAsync(user))
    17. {
    18. // 生成电子邮件确认令牌
    19. var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
    20. // 生成电子邮件的确认链接
    21. var confirmationLink = Url.Action("ConfirmEmail", "Account",
    22. new { userId = user.Id, token = token }, Request.Scheme);
    23. _logger.Log(LogLevel.Warning, confirmationLink);
    24. ViewBag.Message = "如果你在我们系统有注册账户,我们已经发了邮件到您的邮箱中,请前往邮箱激活您的用户。";
    25. // 重定向用户到忘记密码确认视图
    26. return View("ActivateUserEmailConfirmation", ViewBag.Message);
    27. }
    28. }
    29. ViewBag.Message = "请确认邮箱是否存在异常,现在我们无法给您发送激活链接。";
    30. // 为了避免帐户枚举和暴力攻击,所以不进行用户不存在或邮箱未验证的提示
    31. return View("ActivateUserEmailConfirmation", ViewBag.Message);
    32. }
    33. return View();
    34. }
    35. #endregion 激活邮箱

    ActivateUserEmail 视图:

    1. @model EmailAddressViewModel
    2. @{
    3. ViewBag.Title = "激活邮箱";
    4. }
    5. <h2>激活邮箱</h2>
    6. <hr/>
    7. <div class="row">
    8. <div class="col-md-12">
    9. <form method="post">
    10. <div asp-validation-summary="All" class="text-danger"></div>
    11. <div class="form-group">
    12. <label asp-for="Email"></label>
    13. <input asp-for="Email" class="form-control" />
    14. <span asp-validation-for="Email" class="text-danger"></span>
    15. </div>
    16. <button type="submit" class="btn btn-primary">提交</button>
    17. </form>
    18. </div>
    19. </div>

    ActivateUserEmailConfirmation 视图:

    1. @{
    2. ViewBag.Title = "邮件发送通知";
    3. }
    4. <h1 class="text-info">邮箱发送通知</h1>
    5. <h4 class="text-secondary">
    6. @ViewBag.Message
    7. </h4>

    效果:
    image.png
    image.png