在mvc5中获取LoginUserId

时间:2014-03-05 12:35:51

标签: asp.net-mvc asp.net-mvc-5

我使用过这种方法

using Microsoft.AspNet.Identity;
     var currentUser = User.Identity.GetUserId();

但我得到Error Object reference not set to an instance of an object

我也无法像mvc4

那样获得Web安全性和登录用户ID

3 个答案:

答案 0 :(得分:1)

使用如下代码可能会对您有所帮助

public ImportFormFromExcelController()
        : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
    {
    }

    public ImportFormFromExcelController(UserManager<ApplicationUser> userManager)
    {
        UserManager = userManager;
    }

    public UserManager<ApplicationUser> UserManager { get; private set; }

    public Guid getLoginUserInfoId()
    {
        Guid loginUserInfoId = new Guid();
        string loginUserId = User.Identity.GetUserId();
        var searchLoginUserInfoId = from m in db.UserInfos
                                    where
                                        m.UserID == loginUserId
                                    select m;
        foreach (var c in searchLoginUserInfoId)
        {
            loginUserInfoId = c.UserInfoID;
        }
        return loginUserInfoId;
    }

并收到您的登录ID,如

Guid loginUserInfoId = getLoginUserInfoId();

答案 1 :(得分:0)

这是我的一个代码片段中的示例,其中我使用1个DbContext来管理Identity和Model-first类。

假设您尚未扩展IdentityUser模型,则可以使用此方法检索userId:

//Id in Identity is Guid; returning as string for simplicity
public string GetUserId(string username)
{
    var um = new UserManager<IdentityUser>(
                 new UserStore<IdentityUser>(
                     new IdentityDbContext()));
    return um.FindByName(username).Id;
}

如果您使用自定义属性扩展了身份模型,从而创建了自己的模型

public class CustomUserModel : IdentityUser
{
}

...您需要相应地更改上述代码

var um = new UserManager<CustomUserModel>(
             new UserStore<CustomUserModel>(
                 new IdentityDbContext()));

IdentityDbContext也是如此,这是你的DbContext类。

希望这有帮助。

答案 2 :(得分:0)

这解决了我的问题

var LoginuserId=User.Identity.GetUserId();