.Net 7 UserManager.FindByEmailAsync errors with Unable to cast object of type 'System.String' to type 'System.Guid'

25 views Asked by At

I created a new web application based on .Net 7. I had another app that was using .Net 6 that I used to copy some of the authentication and account code over from. In the AccountController, I have a method called ExternalLoginCallback. The SignInManager.ExternalLoginSignInAsync fails, and it goes to the else. It gets the email and then tries to find the user by UserManager.FindByEmailAsync(). This failes with the following error:

"Unable to cast object of type 'System.String' to type 'System.Guid'"

I can't figure out what the issue is. It's obvious that it's trying to convert a string to a guid, but I don't know which one. My code from my ExternalLoginCallBack method is below:

    var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);

    if (result.Succeeded)
    {
        // Update any authentication tokens if login succeeded
        await _signInManager.UpdateExternalAuthenticationTokensAsync(info);

        return RedirectToLocal(returnUrl);
    }
    else
    {
        var email = info.Principal.FindFirstValue(ClaimTypes.Email);

        ApplicationUser theUser = _userManager.FindByEmailAsync(email).Result;

        if (theUser != null)
        {
            IdentityResult identityResult = _userManager.AddLoginAsync(theUser, info).Result;

            if (identityResult.Succeeded)
            {
                //Try to log them in again
                result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);

                if (result.Succeeded)
                {
                    return RedirectToAction("Index", "ObservationLog");
                }
            }
        }

        // If the user does not have an account, then ask the user to create an account.
        ViewData["ReturnUrl"] = returnUrl;
        ViewData["ProviderDisplayName"] = info.ProviderDisplayName;

        return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
    }

Any help would be much appreciated!

0

There are 0 answers