7

也许我以错误的方式处理这个问题,应该在动作过滤器中做所有事情,在这种情况下,请指出我正确的方向!

我正在设置我的 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");

有人可以告诉我这个难题的缺失部分吗?

4

2 回答 2

23

使用RolesAuthorize Action Filter的属性:

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

}

或者使用以下User.IsInRole()方法:

if(User.IsInRole("Administrator")) { ... }
于 2010-01-14T15:48:47.443 回答
3

如果您查看默认 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");
于 2013-07-20T12:49:23.673 回答