ASP.NET Membership - 如何以编程方式确定用户是否在角色中

11

如何确定用户是否具有某个角色?

我已经通过ASP.NET配置安全选项卡设置了所有用户,但现在想在某些关键区域放置逻辑,以便只有特定角色的人才能查看和访问这些区域。

4个回答

23
if (User.IsInRole("rolename")) {
  // my action
}

3
用户是页面(Page)和HttpContext类的属性,因此您可以在页面上简单地使用User进行访问,在非页面文件中使用HttpContext.Current.User进行访问。有关更多信息,请参阅MSDN:http://msdn.microsoft.com/zh-cn/library/system.web.httpcontext.user.aspx - Chris Van Opstal

8

很容易~

HttpContext.Current.User.IsInRole("roleName")

这段代码将查看 SQL 数据库(我的提供程序)以确定在 ASP.NET 中的角色。 - leora
1
是的,它会查看您配置的任何提供商。 - Chris Van Opstal

3

请查看Roles类,特别是IsUserInRole、GetUsersInRole、AddUserToRole等方法。

我经常使用这些方法。


0
感谢 "Chris Van Opstal"。我是这样解决我的问题的,
    public ActionResult Index()
    {

        if (User.IsInRole("Supervisor"))
        {
            return RedirectToAction("Index", "InvitationS");
        }
        return View();
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接