2014-10-09 93 views
1

我正在用ASP.NET Identity 2.0和EF 6.1.1構建一個MVC5應用程序。爲什麼IsInRole總是返回false?

這是我當前的登錄方法的一部分:

[HttpPost] 
    [AllowAnonymous] 
    [ValidateAntiForgeryToken] 
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) 
    { 
     if (!ModelState.IsValid) 
      return View(model); 

     var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: true); 
     switch (result) 
     { 
      case SignInStatus.Success: 
       { 
        var user = await UserManager.FindAsync(model.UserName, model.Password); 

        if (user == null) 
         break; 

        if (!UserManager.IsInRole(user.Id, "OfficeUser")) 
         break; // << I always hit this line - even if the user is an OfficeUser 

這工作得很好,直到我打UserManager.IsInRole()。這總是返回false。

某處我讀到IsInRole()會失敗,如果相應的用戶沒有登錄。但是因爲我通過SignInManager.PasswordSignInAsync()我相信這應該沒問題。

是的,我已經多次檢查數據庫,並且非常仔細;)我的測試用戶和我的測試角色「OfficeUser」明確地分配給對方。

有沒有人有想法?

回答

7

我有同樣的問題,然後我的工作如下。原因似乎是,用戶在此階段未完全簽署或完成所有認證過程。

case SignInStatus.Success: 
       { 
        var user = await UserManager.FindAsync(model.UserName, model.Password); 
        var roles = await UserManager.GetRolesAsync(user.Id) 

        if (user == null) 
         break; 

        if (roles.Contains("OfficeUser")) 
         break; // << I always hit this line - even if the user is an OfficeUser 
+1

是的,這是行得通的。非常感謝,DSR!你剛剛救了我的一天(和週末:)) – Ingmar 2014-10-10 09:37:27

相關問題