ASP.NET Core 2.0 - ASP.NET标识 - 无效的令牌错误

时间:2018-05-10 23:57:47

标签: c# asp.net-core-2.0 asp.net-identity-2

我正在尝试确认来自用户的电子邮件,它始终在开发环境中本地运行,但在托管服务器中始终失败。我不能RDP到这个服务器,这是我订阅的第三方服务器。它给出了#34;无效令牌"每次都有错误。没有其他的。

这有什么解决方法吗?请指教。

由于 亚当

这是代码的生成和编码方式。

    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var newcode = HttpUtility.UrlEncode(code);

这是在“确认电子邮件”中解码和检查代码的方式。动作。

    var newcode = HttpUtility.UrlDecode(code);
var result = await _userManager.ConfirmEmailAsync(user, newcode);

这是生成令牌的完整代码。

        [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        try
        {
            if (ModelState.IsValid)
            {
                string defaultUserRole = "UnAssigned";
                // Send an email with this link
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await _userManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    if (_roleManager != null)
                    {
                        var rolesAdded = await AddRoles();
                        if (rolesAdded == false)
                        {
                            throw new Exception("Unable to add user roles in database.");
                        }
                        var resultAddRole = await _userManager.AddToRoleAsync(user, defaultUserRole);
                        if (resultAddRole.Succeeded == false)
                        {
                            throw new Exception("Unable to add user to UnAssigned Role.");
                        }
                    }
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    var newcode = HttpUtility.UrlEncode(code);
                    var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account", new { userId = user.Id, code = newcode }, protocol: HttpContext.Request.Scheme);
                    await _emailSender.SendEmailAsync(model.Email, "Confirm your account", $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
                    _logger.LogInformation("Email sent.");
                    UserInfoViewModel uiVM = new UserInfoViewModel(user.UserName, user.Email, defaultUserRole);
                    return RedirectToAction(nameof(AccountController.ConfirmRegistration), "Account", uiVM);
                }
                else
                {
                    if (result.Errors.ToList().Count > 0)
                    {
                        string errorInfo = result.Errors.ToList()[0].Code + " : " + result.Errors.ToList()[0].Description;
                        return RedirectToAction(nameof(HomeController.Error), "Home", new { errorMessage = "Result Errors : " + errorInfo });
                    }
                    else
                    {
                        return RedirectToAction(nameof(HomeController.Error), "Home", new { errorMessage = "Unknown error. Please contat system admin." });
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        catch (Exception ex)
        {
            return RedirectToAction(nameof(HomeController.Error), "Home", new { errorMessage = "Final Exception : "+  ex.ToString() });
        }
    }

这是验证令牌的完整代码。这是Visual Studio 2017的默认支架。

        [HttpGet]
    [AllowAnonymous]
    public async Task<IActionResult> ConfirmEmail(string userId, string code)
    {
        try
        {
            if (userId == null || code == null)
            {
                return RedirectToAction(nameof(AccountController.AppsArkLogin), "Account");
            }
            if (_userManager == null)
            {
                throw new Exception("User manager is null.");
            }
            var user = await _userManager.FindByIdAsync(userId);
            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{userId}'.");
            }
            var newcode = HttpUtility.UrlDecode(code);
            var result = await _userManager.ConfirmEmailAsync(user, newcode);
            if (result == null)
            {
                return RedirectToAction(nameof(HomeController.Error), "Home", new { errorMessage = "ConfirmEmailAsync result is null." });
            }
            if (result.Succeeded)
            {
                //return RedirectToAction(nameof(HomeController.Error), "Home", new { errorMessage = "This is working." });
                return View("ConfirmEmail");
            }
            else
            {
                if (result.Errors.ToList().Count > 0)
                {
                    string errorInfo = result.Errors.ToList()[0].Code + " : " + result.Errors.ToList()[0].Description;
                    return RedirectToAction(nameof(HomeController.Error), "Home", new { errorMessage = errorInfo });
                }
                else
                {
                    throw new Exception("Unknown error. Please contact system admin.");
                }
            }
        }
        catch (Exception ex)
        {
            return RedirectToAction(nameof(HomeController.Error), "Home", new { errorMessage = ex.ToString() });
        }
    }

0 个答案:

没有答案