2012-10-03 15 views
1

我試圖在登錄時將用戶重定向到相應的頁面。所以我檢查他們是否在一個角色,然後根據成員身份重定向。但是,Roles.IsUserInRole()似乎不起作用。另外當我使用Roles.GetRolesForUser(「用戶名」)我得到「System.String []」。我正在使用mvc4中的默認簡單成員。我可以看到在數據庫中創建的用戶並鏈接到適當的角色。另外,當我使用[Authorize Roles ..]時,效果很好。這裏是我的登錄(差不多跟我的角色檢查默認的登錄和重定向增加。ASP.Net MVC 4在登錄期間獲取角色重定向到適當的頁面

public ActionResult Login(LoginModel model, string returnUrl) 
     { 
      if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe)) 
      { //Get list of roles to print 
       Session["FName"] = Roles.GetRolesForUser(model.UserName); 
       if(Roles.IsUserInRole(model.UserName,"User")){ 
        return RedirectToAction("Index","UserLanding"); 
        Session["FName"] = "User in User group"; 
       } 
       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); 
     } 

我希望當在他們重定向到UserLanding Congroller索引頁面中的「用戶」組的用戶登錄,但,他們總是被重定向到主頁。

回答

2

我猜你不能訪問Roles.IsUserInRole或GetRolesForUser直到重定向之後,因此空值。我發現這個here下,基於角色的授權。如果有人有辦法直接訪問數據庫中的角色,而不需要通過角色我可以使用它。但在此期間,我將只實現文章中建議的額外重定向。

+0

您無法訪問角色或用戶。原因是Login必須設置cookie,然後頁面加載必須發生,框架才能讀取cookie並創建適當的對象。 –

2

可以驗證用戶手動設置,使您可以訪問成員資格類識別特定用戶,然後就可以訪問諸如角色的所有用戶相關的數據,等等

這裏是你必須添加驗證碼用戶在訪問角色前手動,

Membership.ValidateUser("Username", "PASSWORD"); 
FormsAuthentication.SetAuthCookie(usermaster.Useremail, true); 

希望這個我幫你。 raj

相關問題