2012-12-13 6 views
8

ログイン時にCookieを設定しようとしていますが、ログイン後に現在のユーザーIDを取得する際に問題があります。以下では、intUserIdは-1で、WebSecurity.IsAuthenticatedはfalseです。このコードを置くのは正しい場所ではありませんか?その後、ホームページにリダイレクトされます...なぜこれが正しい場所ではないかわかりません。MVC 4 SimpleMembership - ログイン後にWebSecurity.CurrentUserId -1を返す理由

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

答えて

8

ログインはフォーム認証Cookieのみを設定します。

asp.net認証の仕組みは、要求の認証を設定するためにCookieを読み取る必要がありますが、ログインページの開始時にCookieが存在しないため、フレームワークはユーザーについて何も知らないためです。

ページをリロードすると、情報が表示されます。

これはSimpleMembershipまたはWebSecurityでは新しいものではなく、Forms認証が常に機能する方法です。

+3

私がしたことは、int intUserId2 = WebSecurity.GetUserId(model.UserName);を使用していました。そのユーザーのIDを取得します。助けてくれてありがとう。 –

関連する問題