2

我有 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);
4

1 回答 1

0

我也遇到了这个问题,我尝试了上面的答案,直到没有运气。在 SendAsync 方法中将 isHtml 参数设置为 true 解决了我的问题。

_emailService.SendAsync(vm.Email, "Click the link below to validate.", $"<a href=\"{link}\">Validate email</a>",true);
于 2020-08-15T19:31:07.487 回答