Home > Back-end >  UserManager: How to check if the code generated by GenerateChangeEmailTokenAsync() was used
UserManager: How to check if the code generated by GenerateChangeEmailTokenAsync() was used

Time:04-28

I use UserManager's GenerateChangeEmailTokenAsync() to generate and send the verification code to the new email. I'd like to check if the code has been used in an unauthenticated context and display a message to the user if the new email was verified already: "Your new email address has already been verified. Please log in".

Is there a method in UserManager to accomplish this?

CodePudding user response:

I'm afraid there is no method in userManager can achieve your requirement, But i think you can pass this success message by yourself. You can refer to this code:

            //I use this code to get the currently logged in user
            var user = _userManager.GetUserAsync(User).Result;

            var result = await _userManager.ChangeEmailAsync(user, newEmail, token);

            if (result.Succeeded)
            {
                TempData["Message"] = "Your new email address has already been verified. Please log in";
                return RedirectToAction("ChangeEmail", "Test");
            }
            else
            {
                TempData["Message"] = "Email change failed";
                return RedirectToAction("ChangeEmail", "Test");
            }
        

Test/ChangeEmail

        [HttpGet]
        public IActionResult ChangeEmail()
        {
          //use ViewBag to pass data from controller to view
            ViewBag.Message = TempData["Message"];
            return View();
        }

View

//.....
<h1>@ViewBag.Message</h1>

If change email successfully, it will show message in the view

enter image description here

  • Related