如何在Asp.net Mvc中获取当前登录用户的角色?

时间:2014-06-05 10:53:05

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

我正在编写代码以在if-condition中的Login方法中获取角色,但是它没有返回用户的角色。

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

1 个答案:

答案 0 :(得分:2)

当您致电WebSecurity.Login时,不会自动填充用户的身份验证和角色数据。相反,它们被写入身份验证cookie,只能在下一个请求中读取。

这意味着您只能在用户在登录后重定向到下一页(Roles.GetRolesForUser())后才能阅读Home/Index。这是因为用户做出的下一个请求(无论它可能是什么)现在将附加了身份验证cookie。

当前请求(〜/ login.aspx)没有附加任何身份验证cookie,因此Roles.GetRolesForUser()和类似函数将始终不返回任何内容。