简体   繁体   中英

How to get the roles of current logged-in user in Asp.net Mvc?

I am writing the code to get roles in Login method inside the if-condition but its not returning the roles of the user.

 public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid && WebSecurity.Login(model.Email, model.Password, persistCookie: model.RememberMe))
        {

            List<string> r = Roles.GetRolesForUser().ToList();
            if(r.Contains("Admin"))
            {
                return RedirectToAction("About", "Home");
            }
            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);
    }

When you call WebSecurity.Login the user's authentication and role data is not populated automatically. Instead they are written to the authentication cookie and can only be read on the next request.

This means you can only read from Roles.GetRolesForUser() after the user has been redirected to the next page after login (usually Home/Index ). This is because the next request that the user makes (whatever it might be) will now have the authentication cookie attached to it.

The current request (~/login.aspx) does not have any authentication cookie attached, so Roles.GetRolesForUser() and similar functions will always return nothing.

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