使用MVC 5的身份,在登录之后无法获得用户名 [英] Using MVC 5's identity, can't get user name right after logging in

查看:164
本文介绍了使用MVC 5的身份,在登录之后无法获得用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用MVC 5的身份解决方案,但卡住了的东西,应该是很简单的:我要上的AccountController的登录方法来获取loged用户的姓名验证模型之后(和我不不想从模型中使用它!)。

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!).

下面是我的一块code的:

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
}

这是我得到的问题是,这个属性为null。

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?

推荐答案

在其执行链的末端 SignInManager.PasswordSignInAsync 方法调用 SignInAsync 方法,它基本上是负责制定,其中包含有关用户的多重索赔身份验证Cookie(其中一个是它的名字)。为什么你不能使用的原因 User.Identity.Name SignInManager.PasswordSignInAsync 相同的呼叫是 User.Identity 填写与身份验证cookie的债权(其中尚未解析)。它工作在二传的原因是,该cookie是存在的,User.Identity正确填写。大多数成功登录后的时间有一个重定向到一些页面。这里面重定向动作,你将能够使用 User.Identity 由于cookie已设置。

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.

这篇关于使用MVC 5的身份,在登录之后无法获得用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆