简体   繁体   中英

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

I think same thing happening in MVC as well.

You can get the user details by passing model.UserName as follows.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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