最核心的一句代码:
    var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);

    生成的确认链接:
    http://localhost:3290/Account/ConfirmEmail?userId=ee5d09fb…&token=CfDJ8OM7Qj…

    在 Startup 中修改 Identity 配置:

    1. public void ConfigureServices(IServiceCollection services)
    2. {
    3. ...
    4. services.AddIdentity<ApplicationUser, IdentityRole>()
    5. .AddErrorDescriber<CustomIdentityErrorDescriptor>()
    6. .AddEntityFrameworkStores<AppDbContext>()
    7. .AddDefaultTokenProviders();
    8. ...
    9. }

    AdminController 中添加确认邮箱:

    1. [HttpGet]
    2. public async Task<IActionResult> ConfirmEmail(string userId, string token)
    3. {
    4. if (userId == null || token == null)
    5. {
    6. return RedirectToAction("index", "home");
    7. }
    8. var user = await _userManager.FindByIdAsync(userId);
    9. if (user == null)
    10. {
    11. ViewBag.ErrorMessage = $"当前{userId}无效";
    12. return View("NotFound");
    13. }
    14. var result = await _userManager.ConfirmEmailAsync(user, token);
    15. if (result.Succeeded)
    16. {
    17. return View();
    18. }
    19. ViewBag.ErrorTitle = "您的电子邮箱尚未进行验证。";
    20. return View("Error");
    21. }

    ConfirmEmail 对应的视图:

    1. <h3>您的电子邮件已经验证成功</h3>
    2. <a asp-controller="Home" asp-action="Index">返回首页</a>

    注册时检查邮箱是否已验证:

    1. [HttpPost]
    2. public async Task<IActionResult> Register(RegisterViewModel model)
    3. {
    4. if (ModelState.IsValid)
    5. {
    6. var user = new ApplicationUser
    7. {
    8. UserName = model.Email,
    9. Email = model.Email,
    10. City = model.City
    11. };
    12. var result = await _userManager.CreateAsync(user, model.Password);
    13. if (result.Succeeded)
    14. {
    15. // 生成电子邮件确认令牌
    16. var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
    17. // 生成电子邮件的确认链接
    18. var confirmationLink = Url.Action("ConfirmEmail", "Account",
    19. new { userId = user.Id, token = token }, Request.Scheme);
    20. _logger.Log(LogLevel.Warning, confirmationLink);
    21. if (_signInManager.IsSignedIn(User) && User.IsInRole("Admin"))
    22. {
    23. return RedirectToAction("ListUsers", "Admin");
    24. }
    25. ViewBag.ErrorTitle = "注册成功";
    26. ViewBag.ErrorMessage = "在你登入系统前,我们已经给您发了一份邮件,需要您先进行邮件验证,点击确认链接即可完成。";
    27. return View("Error");
    28. }
    29. foreach (var error in result.Errors)
    30. {
    31. ModelState.AddModelError(string.Empty, error.Description);
    32. }
    33. }
    34. return View(model);
    35. }