简体   繁体   中英

ASP.NET MVC4 c# : Get user roles

This is the code I used for membership in 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
                }
            }
        }
    }

I'm trying to redirect the user for different view if his Role is "Manager",this is what I tried to get the user roles in the controller but It returns an empty list :

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

You should be able to call .IsInRole()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM