MVC 4 SimpleMembership - Why WebSecurity.CurrentUserId -1 after login

情到浓时终转凉″ 提交于 2019-12-28 04:26:16

问题


I am trying to set a cookie upon login and having issues with getting the current user id after login. In the below, intUserId is -1 and WebSecurity.IsAuthenticated is false. Is this not the correct place to put this code? After this, it redirects to the home page...so not sure why this is not the correct place.

// POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                //TODO: set current company and facility based on those this user has access to
                int intUserId = WebSecurity.GetUserId(User.Identity.Name);
                int intUserId2 = WebSecurity.GetUserId(model.UserName);
                UserSessionPreferences.CurrentCompanyId = 1;
                UserSessionPreferences.CurrentFacilityId = 1;

                return RedirectToLocal(returnUrl);
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }

回答1:


Login only sets the Forms Authentication cookie.

The way asp.net authentication works is that it must read the cookie to set the authenticate the request, but since the cookie did not exist when the Login page was started, the framework doesn't know anything about the user.

Reload the page, and you will find the information is available.

FYI, this is nothing new with SimpleMembership or WebSecurity, this is the way Forms Authentication has always worked.



来源:https://stackoverflow.com/questions/13850861/mvc-4-simplemembership-why-websecurity-currentuserid-1-after-login

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!