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 に答える