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

本文关键字:获取 用户 角色 NET MVC4 ASP | 更新日期: 2023-09-27 18:08:03

这是我用于全局成员的代码。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
                }
            }
        }
    }

我试图重定向用户不同的视图,如果他的角色是"经理",这就是我试图在控制器中获得用户角色,但它返回一个空列表:

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

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

你应该能够调用。isinrole ()

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