2014-06-09 83 views
0

這是我在Global.asax中ASP.NET MVC4 C#:獲取用戶角色

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) 
    { 
     if (FormsAuthentication.CookiesSupported == true) 
     { 
      if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) 
      { 
       try 
       { 

        //let us take out the username now     
        string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; 
        string roles = string.Empty; 

        IUserService _userService= new UserService(); 
        UserViewModel user = _userService.SelectUserByUserName(username).UserList.FirstOrDefault(); 
        roles = user.role; 

        //let us extract the roles from our own custom cookie 


        //Let us set the Pricipal with our user specific details 
        HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
         new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(',')); 
       } 
       catch (Exception) 
       { 
        //somehting went wrong 
       } 
      } 
     } 
    } 

我試圖將用戶重定向不同的看法,如果他的角色是「經理人」用於成員的代碼,這就是我試圖讓在控制器中的用戶角色,但它返回一個空列表:

[Authorize(Roles = "admin, manager")] 
     public ActionResult Index() 
     { 

      string[] rolesArray; 
      rolesArray = Roles.GetAllRoles();// returns an empty array 
      foreach(var item in rolesArray){ 
       if(item == "manager"){ 
        return RedirectToAction("index", "Manager"); 
       } 
      } 
      return View(); 
     } 
+0

有什麼代碼爲'Roles.GetAllRoles()?' – Icarus

回答

2

你應該能夠調用.IsInRole()

if (User.IsInRole("manager")) 
{ 
    return RedirectToAction("index", "Manager"); 
}