简体   繁体   English

用户登录时立即将用户信息添加到会话数据中

[英]Adding user info to session data right when user logins

I currently have the following login script: 我目前有以下登录脚本:

[HttpPost]
        public ActionResult LogOn(LogOnModel model)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    Guid MyUserId = (Guid)Membership.GetUser().ProviderUserKey;
                    System.Web.HttpContext.Current.Session[MyUserId.ToString()] = profileRepository.GetFullProfile(MyUserId);
                    return Json(true);                  
                }
                else
                {
                    return Json("The user name or password provided is incorrect.");
                }
            }else
                return Json("The user name or password provided is incorrect.");

        }

I get an error on the Membership.GetUser() saying the object reference error. 我在Membership.GetUser()上收到一个错误,说该object reference错误。 I researched this and i found it was because only my next http request will be authenticated, so what is the best way to save a user's data into session when the user logins? 我对此进行了研究,发现这是因为只有下一个http请求将通过身份验证,所以在用户登录时将用户数据保存到会话中的最佳方法是什么? will it be assured to be in the session until the user's session expires and kicks him out or will there ever be an instance where the user is logged in without the session data set? 是否可以确保一直存在到会话中,直到用户的会话到期并将其踢出去,还是会出现用户没有会话数据集登录的实例? If so ill need something to handle that as well. 如果有病,也需要一些东西来处理。

This has happened to me in LoginButton_Clicked in an asp.net application (Not MVC). 我在asp.net application (不是MVC)中的LoginButton_Clicked中发生了这种情况。 Even thought this event ( LoginButton_Clicked ) fires after a successful login Membership.GetUser(), Roles.GetRolesForUser(), Profile Are yet filled in. Therefore username needs to be passed into each method to get the details. 甚至以为成功登录后会触发此事件( LoginButton_Clicked )Membership.GetUser(),Roles.GetRolesForUser(),Profile尚未填写。因此,需要将用户名传递给每个方法以获取详细信息。

I think same thing happening in MVC as well. 我认为MVC中也发生了同样的事情。

You can get the user details by passing model.UserName as follows. 您可以通过传递model.UserName来获取用户详细信息,如下所示。

MembershipUser mu = Membership.GetUser(model.UserName);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM