MVC 4 SimpleMembership - 登录后为什么WebSecurity.CurrentUserId -1

Cha*_*son 8 asp.net-mvc simplemembership

我正在尝试在登录时设置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);
        }
Run Code Online (Sandbox Code Playgroud)

Eri*_*sch 8

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

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

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

仅供参考,这对于SimpleMembership或WebSecurity来说并不是什么新鲜事,这是表单身份验证始终有效的方式.

  • 好的,我所做的是使用int intUserId2 = WebSecurity.GetUserId(model.UserName); 获得该用户的ID.谢谢您的帮助. (3认同)