如何在视图中使用MVC角色权限?

时间:2014-11-23 21:37:07

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

如何根据角色中的一组用户在视图中应用权限。

例如,如何为角色编辑器显示“创建文章”按钮并将其隐藏为角色阅读器?

2 个答案:

答案 0 :(得分:7)

最佳做法是让Controller在ViewModel上设置属性,然后View可以检查这一点,它也使逻辑更容易测试。

它的模型工作是与视图的沟通。
然后安全逻辑不会泄漏到视图中。

在您的控制器中,您可以执行以下操作:

model.IsEditor = User.IsInRole("editor")
model.IsReader = User.IsInRole("reader")

然后,如果您查看,您可以执行以下操作:

@if (model.IsEditor)
{
  // show editor button
}

@if (model.IsReader)
{
  // show reader button
}

答案 1 :(得分:4)

这有两种思想流派。

一所学校说您为角色创建了单独的视图。因此,您可以创建RoleEditor视图和RoleReader视图。而且,在相对简单的应用程序中,这可能是最好的方法。

如果您的观点更复杂,并且需要基于角色的“即时”渲染,那么您会采用更像Ralph建议的方法。你做这样的事情:

public ActionResult Index() {
    // IsUserAnEditor is a placeholder for a method to determine whether the user
    // is an editor based on whatever role technology you're using.
    MyModel model = new MyModel { IsEditor = IsUserAnEditor() }
    return View(model);
}

然后在您看来,您有这样的代码:

@model MyModel

....

@if(Model.IsEditor)
{
    // Code to add the "Edit" link, this is just an example, customize for your needs
    <span>
    @Html.ActionLink("Edit", "Edit", "MyController", new { id=Model.ID })
    </span>
}