我有 ASP.NET Core web api 项目,我需要确认电子邮件。一切正常,生成的令牌和在 ConfirmEmail() 方法中收到的令牌是相等的。令牌似乎有效,但结果给出了无效的令牌:
var result = await userManager.ConfirmEmailAsync(user, code);
生成令牌:
var code = await userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
var email = user.Email;
await emailSender.SendEmailConfirmationAsync(email, callbackUrl);
EmailConfirmationLink() 和 SendEmailConfirmationAsync() 方法:
public static string EmailConfirmationLink(this IUrlHelper urlHelper, string userId, string code, string scheme)
{
var result = urlHelper.Action(
action: "ConfirmEmail",
controller: "ApplicationUsers",
values: new { userId, code },
protocol: scheme);
return result;
}
public static Task SendEmailConfirmationAsync(this IEmailSender emailSender, string email, string link)
{
return emailSender.SendEmailAsync(email, "Confirm your email",
$"Please confirm your account by clicking this link: <a href='{HtmlEncoder.Default.Encode(link)}'>Confirm email</a>");
}
ConfirmEmail() 方法:
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
// ....
}
var user = await userManager.FindByIdAsync(userId);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userId}'.");
}
var result = await userManager.ConfirmEmailAsync(user, code);