I'm trying to use the MVC 5's identity solution, but got stuck on something that should be very simple: I want the login method on the AccountController to get the loged user's name right after validating the model (and I don't want to use it from the model!).
Here's a piece of my code:
var result = await SignInManager.PasswordSignInAsync(model.Login, model.Password, false, shouldLockout: false);
string NomeUsuario = "";
if (result == SignInStatus.Success)
{
NomeUsuario = User.Identity.Name; //<== getting the logged user's name
}
The problem that I'm getting is that this property is null.
After a lot of tests, I realized something odd: if I authenticate twice, on the second pass, it will work. But every time I logoff and try to login in again, it will get null on the user's name.
Any help on what's wrong with that?
If you need to get the user from within the controller, use the User property of Controller. If you need it from the view, I would populate what you specifically need in the ViewData , or you could just call User as I think it's a property of ViewPage .
string username = currentUser. UserName; //Get UserId of Currently logged in user.
At the end of its execution chain SignInManager.PasswordSignInAsync
method calls for SignInAsync
method which is basically responsible for setting an authentication cookie which contains multiple claims about a user (one of them is it's name). The reason why you can't use User.Identity.Name
in the same call with SignInManager.PasswordSignInAsync
is that User.Identity
filled out with the claims from authentication cookie (which are not parsed yet). The reason that it works on the second pass is that the cookie is there and User.Identity is properly filled. Most of the time after a successful login there is a redirect to some page. Inside this redirect action you will be able to use User.Identity
since the cookie is already set.
I've found you can go right back to the UserManager and look them up:
var user = await UserManager.FindAsync(username, password);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With