获取登录用户的用户名的在Asp.Net MVC 5 [英] Get UserID of logged-in user in Asp.Net MVC 5

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

问题描述

我是比较新的ASP.Net MVC和现在尝试使用内置的用户登录功能。我能够在登记注册视图中的用户。如果我尝试用创建的用户登录,这也有效。我重定向到母版页。

I'm relatively new to ASP.Net MVC and try to use the built-in user login functionality now. I'm able to register an user in the registration view. If I try to login with the created user this also works. I'm redirected to the master page.

但我不能够获得当前用户的用户ID。我想我的code在HomeController中,并在的AccountController,但都没有奏效。在第一行的语句返回始终为空。

But I'm not able to get the UserID of the current user. I tried my code in the HomeController and in the AccountController, but both didn't work. The statement in the first line returns always null.

var userID = User.Identity.GetUserId();

if (!string.IsNullOrEmpty(userID))
{
    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ApplicationDbContext.Create()));
    var currentUser = manager.FindById(User.Identity.GetUserId());
}

我一定要到别的获取用户名之前?

Do I have to to something else before getting the UserID?

推荐答案

答案是在你的code那里。这是什么回报?

The answer is right there in your code. What does this return?

var userID = User.Identity.GetUserId();

如果您使用的是ASP.NET身份,然后点击日志记录(和重定向到另一页), IPrincipal.IIdentity 应一个 ClaimsIdentity 。你可以试试这个:

If you are using ASP.NET Identity, then after logging in (and redirecting to another page), the IPrincipal.IIdentity should be a ClaimsIdentity. You can try this:

var claimsIdentity = User.Identity as ClaimsIdentity;
if (claimsIdentity != null)
{
    // the principal identity is a claims identity.
    // now we need to find the NameIdentifier claim
    var userIdClaim = claimsIdentity.Claims
        .FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);

    if (userIdClaim != null)
    {
        var userIdValue = userIdClaim.Value;
    }
}

code的上述块是不完全的,但本质上,是什么 IIdentity.GetUserId 扩展方法一样。

如果没有这工作的,那么用户可能没有真正登录到你的网站呢。登录后,你必须重定向到另一个页面之前,服务器将写入验证cookie的浏览器。此cookie前必须写在 User.Identity 的这一切理赔信息(包括的NameIdentifier )的在后续请求

If none of this works, then the user may not really be logged into your site yet. After logging in, you have to redirect to another page before the server will write the authentication cookie to the browser. This cookie must be written before the User.Identity has all of this claims information (including the NameIdentifier) on subsequent requests.

这篇关于获取登录用户的用户名的在Asp.Net MVC 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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