0

In my MVC5 ASP.NET C# application, I want to store some important but temporary data in the session. For that I tried to set the session on receipt of signin success as following:-

public class AccountController: Controller
{
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
    .
    .
    var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.rememberMe, shouldLockout= false);

    switch (result){
        case SignInStatus.Success:
            var user =  UserManager.FindById(User.Identity.GetUserId());
            return RedirectToLocal(returnUrl);
        .
        .
        }
}

whilst this one fails , calling User.Identity.GetUserId() inside the HomeController return the correct result.

Can anyone please explain why this happens and how can get the Current user after Signing in so as to set the session.

UPDATE

I have now retrieved the User object by using method UserManager.FindBynameAsync(model.UserName). However I still cannot figure out why the UserId is not available despite of SignIn success.

Abhishek
  • 63
  • 2
  • 10
  • Probably `SignInManager.PasswordSignInAsync` is not enough, instead, use something like `var user = UserManager.FindByName(model.UserName);`. – Slava Utesinov Feb 12 '18 at 06:14
  • 1
    It is possible you've encoutered similar issue like this one: https://stackoverflow.com/questions/33951881/user-identity-getuserid-returns-null-after-successful-login. `User.Identity` usually not work in the same login action, you'll have to wait until next request. – Tetsuya Yamamoto Feb 12 '18 at 06:16
  • @SlavaUtesinov Thanks for prompt response. I also simultaneously discovered that from the function `SendCode(string returnUrl, bool rememberMe)` in `AccountsController`. I have updated my question now. – Abhishek Feb 12 '18 at 06:18
  • @Tetsuya Wow, that post clears all my doubts. Please post your comment as the Answer so that I can accept it – Abhishek Feb 12 '18 at 06:21

0 Answers0