Using MVC 5's identity, can't get user nam

2019-06-16 10:18发布

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?

2条回答
我只想做你的唯一
2楼-- · 2019-06-16 10:59

I've found you can go right back to the UserManager and look them up:

var user = await UserManager.FindAsync(username, password);
查看更多
放荡不羁爱自由
3楼-- · 2019-06-16 11:11

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.

查看更多
登录 后发表回答