最核心的一句代码:var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
生成的确认链接:
http://localhost:3290/Account/ConfirmEmail?userId=ee5d09fb…&token=CfDJ8OM7Qj…
在 Startup 中修改 Identity 配置:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddErrorDescriber<CustomIdentityErrorDescriptor>()
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
...
}
AdminController 中添加确认邮箱:
[HttpGet]
public async Task<IActionResult> ConfirmEmail(string userId, string token)
{
if (userId == null || token == null)
{
return RedirectToAction("index", "home");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
ViewBag.ErrorMessage = $"当前{userId}无效";
return View("NotFound");
}
var result = await _userManager.ConfirmEmailAsync(user, token);
if (result.Succeeded)
{
return View();
}
ViewBag.ErrorTitle = "您的电子邮箱尚未进行验证。";
return View("Error");
}
ConfirmEmail 对应的视图:
<h3>您的电子邮件已经验证成功</h3>
<a asp-controller="Home" asp-action="Index">返回首页</a>
注册时检查邮箱是否已验证:
[HttpPost]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
City = model.City
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// 生成电子邮件确认令牌
var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
// 生成电子邮件的确认链接
var confirmationLink = Url.Action("ConfirmEmail", "Account",
new { userId = user.Id, token = token }, Request.Scheme);
_logger.Log(LogLevel.Warning, confirmationLink);
if (_signInManager.IsSignedIn(User) && User.IsInRole("Admin"))
{
return RedirectToAction("ListUsers", "Admin");
}
ViewBag.ErrorTitle = "注册成功";
ViewBag.ErrorMessage = "在你登入系统前,我们已经给您发了一份邮件,需要您先进行邮件验证,点击确认链接即可完成。";
return View("Error");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
return View(model);
}