ASP.NET MVC检查用户是否属于[x]组

时间:2010-01-14 15:43:38

标签: asp.net-mvc authentication authorization usergroups

也许我正在以错误的方式接近这个并且应该在行动过滤器中做所有事情,在这种情况下,请指出我正确的方向!

我正在设置我的ASP.NET MVC应用程序,以便一个HomeController Index操作提供两种不同类型的内容,如下所示:

if(Request.IsAuthenticated)
  return View("IndexRegistered");
else
  return View("IndexGuest");

这很好,但是我想将它拆分为三个,以便管理员成员获得他们自己的页面......

if(Request.IsAuthenticated)
{
  if( /* user is a member of administrators */)
    return View("IndexAdministrator");
  else
    return View("IndexCustomer");
}
else
  return View("IndexGuest");

有人可以告诉我这个谜题的遗失吗?

2 个答案:

答案 0 :(得分:21)

使用授权RolesAction Filter属性:

[Authorize(Roles="Administrators,Moderators")]
public ActionResult SomeAction(){

}

或使用User.IsInRole()方法:

if(User.IsInRole("Administrator")) { ... }

答案 1 :(得分:2)

如果您查看默认MVC项目模板中开箱即用的身份验证提供程序,可以轻松地在那里添加自己的角色支持并在会话中跟踪它,因此上面的代码将成为:

if(Request.IsAuthenticated)
{
  if(Session["Role"] == "Administrator")
    return View("IndexAdministrator");
  else
    return View("IndexCustomer");
}
else
  return View("IndexGuest");

然后打开可能性:

if(Request.IsAuthenticated)
  return View("Index" + Session["Role"]);
else
  return View("IndexGuest");
相关问题