繁体   English   中英

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

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

我正在编写代码以在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);
    }

当您调用WebSecurity.Login ,不会自动填充用户的身份验证和角色数据。 而是将它们写入身份验证cookie,并且只能在下一个请求时读取。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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