2013-08-31 18 views
0

好吧,一個下午下來,我答應了SO的幫助。我的登錄方法非常標準。如下所示,我使用WebSecurity.Login。MVC4 WebSecurity.Login第一次通過失敗,無法通過登錄方法獲取用戶

之後,我想運行一次檢查來查看用戶的配置文件是否已完成,如果沒有,請將它們發送到該視圖。

控制器

[AllowAnonymous] 
[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Login(LoginModel model, string returnUrl) 
{ 
    if (ModelState.IsValid && WebSecurity.Login(model.Email, model.Password, persistCookie: model.RememberMe)) 
    { 

     if (!User.IsInRole("User")) 
     { 
      if (!IsProfileComplete(WebSecurity.GetUserId(User.Identity.Name))) 
      { 
       return RedirectToAction("ProfileCompletion"); 
      } 

      if(!User.IsInRole("User")) Roles.AddUserToRole(User.Identity.Name, "Vendor"); 
     } 
     else // user has role 
     { 
      return RedirectToAction("Index", "Dashboard"); 
     } 
    } 

    ModelState.AddModelError("", "Unknown username or password."); 
    return View(model); 
} 

我已經通過它加強了一堆.... WebSecurity.Login後,我的印象中WebSecurity用戶數據會得到確定,但WebSecurity.GetUserId(User.Identity .NAME)回來爲-1

即使當用戶完成配置文件,將其重定向到配置文件完成,因爲它試圖查找配置文件的用戶ID -1

有什麼關於我缺少的http post和登錄上下文集?我正在尋找的最終結果是確保用戶在進入系統之前完成了配置文件頁面。也許有更好的方法來做到這一點?

編輯-----

發現這個鏈接,但我仍然欣賞一個快速評論,如果有人能提出一個更好的模式爲我所期望的功能

MVC 4 SimpleMembership - Why WebSecurity.CurrentUserId -1 after login

回答

1

視後你發現指出登錄後沒有立即設置用戶身份,所以User.Identity.Name不包含用戶名。改爲使用model.UserName。嘗試改變這一行:

if (!IsProfileComplete(WebSecurity.GetUserId(User.Identity.Name))) 

要這樣:

if (!IsProfileComplete(WebSecurity.GetUserId(model.UserName)))