8

我正在尝试在登录时设置一个 cookie,并且在登录后获取当前用户 ID 时遇到问题。在下面,intUserId 为 -1,WebSecurity.IsAuthenticated 为 false。这不是放置此代码的正确位置吗?在此之后,它重定向到主页......所以不知道为什么这不是正确的地方。

// 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);
        }
4

1 回答 1

8

登录仅设置表单身份验证 cookie。

asp.net 身份验证的工作方式是它必须读取 cookie 来设置对请求的身份验证,但是由于在登录页面启动时 cookie 不存在,因此框架对用户一无所知。

重新加载页面,您会发现信息可用。

仅供参考,这对于 SimpleMembership 或 WebSecurity 来说并不是什么新鲜事,这是表单身份验证一直以来的工作方式。

于 2012-12-13T00:11:04.683 回答