ASP.NET MVC4 c#:获取用户角色

时间:2014-06-09 22:53:22

标签: c# asp.net .net asp.net-mvc

这是我用于Global.asax会员资格的代码

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
                }
            }
        }
    }

我尝试将用户重定向到不同的视图,如果他的角色是&#34;经理&#34;,这是我试图在控制器中获取用户角色但它返回一个空列表:< / p>

[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();
        }

1 个答案:

答案 0 :(得分:2)

你应该可以调用.IsInRole()

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