2014-06-25 66 views
1

我在ASP.NET MVC 4項目中使用SimpleMembership。我登錄後,我無法獲得當前用戶名和當前用戶ID,這裏是我的登錄功能:ASP.NET MVC 4 Websecurity.CurrentUserId返回-1

[HttpPost] 
     public ActionResult Login(FormCollection form) 
     { 
      bool success = WebSecurity.Login(form["username"], form["password"], false); 
      if (success) 
      { 
       string returnUrl = Request.QueryString["ReturnUrl"]; 
       if (returnUrl == null) 
       { 
        Response.Redirect("~/home/index?userId=" + WebSecurity.CurrentUserId + "&userName=" + WebSecurity.currentUserName); 
       } 
       else 
       { 
        Response.Redirect(returnUrl); 
       } 
      } 
      return View(); 
     } 

在此行中Response.Redirect("~/home/index?userId=" + WebSecurity.CurrentUserId + "&userName=" + WebSecurity.currentUserName); WebSecurity.CurrentUserId回報-1WebSecurity.currentUserName回報""

我缺少的東西?任何幫助將非常感激。

然而在我看來,如果我這樣做@{ int value; value = WebSecurity.currentUserID; } @{ ViewBag.Title = value; }在瀏覽器標題是正確的currentUserId

+0

爲什麼你需要將這些項目添加到URL? – TheNorthWes

回答

1

試試這個

[HttpPost] 
      public ActionResult Login(FormCollection form) 
      { 
       bool success = WebSecurity.Login(form["username"], form["password"], false); 
       if (success) 
       { 
        var userId = WebSecurity.GetUserId(form["username"]); 
        string returnUrl = Request.QueryString["ReturnUrl"]; 
        if (returnUrl == null) 
        { 
         Response.Redirect("~/home/index?userId=" + userId + "&userName=" + WebSecurity.currentUserName); 
        } 
        else 
        { 
         Response.Redirect(returnUrl); 
        } 
       } 
       return View(); 
      } 

WebSecurity不會內在直到重定向完成(設計)。解決方法是在登錄成功後通過用戶名獲得用戶ID

+0

什麼是LoginModel?當我添加它時,我得到一個命名空間錯誤 – user3723240

+0

我的答案適合MVC ASP.net。讓我爲你更新 – PaulBinder

+0

非常感謝。 – user3723240

1

MSDN:

當用戶登錄時,ASP.NET將在認證令牌 cookie讓ASP.NET知道後續請求中用戶已登錄的 。如果persistCookie爲false,則令牌僅在用戶關閉瀏覽器之前有效地爲 。

所以它只能用於登錄後的請求。用途:

WebSecurity.GetUserId(username);