ASP.NET Core Identity: redirect to profile

Thomas Gerodimos 21 Reputation points
2022-11-09T08:24:45.46+00:00

I am developing an ASP.NET Core (razor pages) site. I have extended the Identity user and added some extra fields (image 1).
I want to redirect a loged in user to profile page if the extra fields are not completed and redirect to root page if profil is completed.

So in the login page I tried to add:

if (ModelState.IsValid)  
            {  
                // This doesn't count login failures towards account lockout  
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true  
                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);  
                if (result.Succeeded)  
                {  
                    _logger.LogInformation("User logged in.");  
                      
                    var currentUser = await _signInManager.UserManager.GetUserAsync(User);  
  
                    if (!string.IsNullOrEmpty(currentUser.FirstName))  
                    {  
                        returnUrl ??= Url.Content("~/");  
                    }  
                    else  
                    {  
                        returnUrl ??= Url.Content("~/Identity/Account/Manage");  
                    }  
  
  
                    return LocalRedirect(returnUrl);  

If I run the app I keep geting currentUser object null.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,166 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,011 Reputation points Microsoft Vendor
    2022-11-10T03:03:45.437+00:00

    Hi @Thomas Gerodimos ,

    var currentUser = await _signInManager.UserManager.GetUserAsync(User)    
    

    The issue relates above code, if you set a break point to check the User, you can see it doesn't contain the login user.

    To find the current user after login success, you can try to use the FindByEmailAsync method, code like this:

    var currentUser = await _signInManager.UserManager.FindByEmailAsync(Input.Email);  
    

    The result as below:

    258983-image.png

    Besides, the UserManager also provide method to find the user by id or name, you can check the UserManager<TUser> Class


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Thomas Gerodimos 21 Reputation points
    2022-11-10T16:50:54.92+00:00

    Thanks, it worked.

    0 comments No comments