如何使用视图中的一个MVC角色权限?视图、如何使用、权限、角色

2023-09-04 13:02:03 作者:堇墨浮华

如何申请许可,基于一组用户的角色视图。

How can I apply permission in a View based on a Set of users in a Role.

例如,我怎么能显示出一个角色编辑器创建项目按钮,并隐藏了一个角色阅读器?

For example, how can I show a Create Article button for a role Editor and hide it for a role Reader?

推荐答案

它的最佳实践来获得控制器设置在视图模型的属性,然后在视图可以检查这一点,这也使得逻辑更容易测试。

Its best practice to get the Controller to set a property on the ViewModel, then the View can check for this and it also makes the logic more easily testable.

它的模型的工作就是要与视图的传播者。 然后,安全逻辑不会泄漏到视图。

Its the Models job is to be the communicator with the View. Then security logic doesn't leak into the View.

在你的控制器,你可以这样做:

In your controller you could do something like:

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

然后,如果你查看​​你能做到以下几点:

Then if you view you could do the following:

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

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