添加邮箱激活功能,使用户能主动激活邮箱:
添加 ViewModel:
public class EmailAddressViewModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
}
修改 AccountController,添加激活邮箱相关的逻辑:
#region 激活邮箱
[HttpGet]
public IActionResult ActivateUserEmail()
{
return View();
}
[HttpPost]
public async Task<IActionResult> ActivateUserEmail(EmailAddressViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByEmailAsync(model.Email);
// 当前已经存在老用户时 1.生成电子令牌 2.以及电子令牌确认URL
if (user != null)
{
if (!await _userManager.IsEmailConfirmedAsync(user))
{
// 生成电子邮件确认令牌
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);
ViewBag.Message = "如果你在我们系统有注册账户,我们已经发了邮件到您的邮箱中,请前往邮箱激活您的用户。";
// 重定向用户到忘记密码确认视图
return View("ActivateUserEmailConfirmation", ViewBag.Message);
}
}
ViewBag.Message = "请确认邮箱是否存在异常,现在我们无法给您发送激活链接。";
// 为了避免帐户枚举和暴力攻击,所以不进行用户不存在或邮箱未验证的提示
return View("ActivateUserEmailConfirmation", ViewBag.Message);
}
return View();
}
#endregion 激活邮箱
ActivateUserEmail 视图:
@model EmailAddressViewModel
@{
ViewBag.Title = "激活邮箱";
}
<h2>激活邮箱</h2>
<hr/>
<div class="row">
<div class="col-md-12">
<form method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Email"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">提交</button>
</form>
</div>
</div>
ActivateUserEmailConfirmation 视图:
@{
ViewBag.Title = "邮件发送通知";
}
<h1 class="text-info">邮箱发送通知</h1>
<h4 class="text-secondary">
@ViewBag.Message
</h4>
效果: