twitter-bootstrap ASP.NET MVC 5 基于用户角色自定义 Bootstrap 导航栏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22305497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC 5 Customise Bootstrap navbar based on User Role
提问by ASPCoder1450
I'm using the ASP.NET MVC 5 built in authentication methods. I would like to show and hide links (in the menu navbar) based on the role the user is in.
我正在使用 ASP.NET MVC 5 内置的身份验证方法。我想根据用户所在的角色显示和隐藏链接(在菜单导航栏中)。
Has anyone acheived this?
有没有人做到了这一点?
Where would be a starting point?
起点在哪里?
回答by Chris Pratt
Just wrap your links in:
只需将您的链接包装在:
@if (User.IsInRole("SomeRole"))
{
...
}
回答by markpsmith
You can use MvcSiteMapfor this. It has a feature called SecurityTrimming which uses the [Authorize] attribute on your action methods to decide whether or not to display the menu item.
您可以为此使用MvcSiteMap。它有一个称为 SecurityTrimming 的功能,它使用您的操作方法上的 [Authorize] 属性来决定是否显示菜单项。
I know it's frowned upon to post a links in answers but I found this blog postvery useful.
我知道在答案中发布链接是不受欢迎的,但我发现这篇博文非常有用。
In addition to the role-based menu visibility, I added custom attributes to the MvcSiteMapNodes to determine visibility of links that were accessible to users but I didn't want shown in the menu (e.g. Edit pages), and I also added icon attributes which allowed me to use the bootstrap menu icons e.g:
除了基于角色的菜单可见性之外,我还向 MvcSiteMapNodes 添加了自定义属性,以确定用户可以访问但我不想在菜单中显示的链接的可见性(例如编辑页面),并且我还添加了图标属性允许我使用引导菜单图标,例如:
<mvcSiteMapNode title="Till" controller="Home" action="Index" area="Till" iconClass="icon-home" visibility="true">
I went a bit off-topic there, but I just wanted to highlight how flexible MvcSiteMap is.
我在那里有点跑题,但我只是想强调 MvcSiteMap 是多么灵活。
回答by Michael
Two things I do. Either
我做两件事。任何一个
User.IsInRole(admin)
{link somewhere}
Or what I personally do is because I use areas I have a viewstart in area admin which links to admin shared viewmodel then in admin shared view that links to the public view.
或者我个人做的事情是因为我使用了区域管理中的视图开始,它链接到管理共享视图模型,然后在管理共享视图中链接到公共视图。
In the admin shared view. I set up a section. Inside this section I define extra nav details what that specific role will see and add them in a list tag
在管理员共享视图中。我设置了一个部分。在本节中,我定义了额外的导航详细信息该特定角色将看到的内容并将它们添加到列表标签中
Then inside public shared view I then use (on phone can't remember exact name something like)
Html.IsSectionDefined
然后在公共共享视图中我然后使用(在手机上不记得确切的名称)
Html.IsSectionDefined
I personally like the second method using areas and sections both would work fine but with the second I find it much cleaner and you can be so much more specific and much simpler
我个人喜欢使用区域和部分的第二种方法都可以正常工作,但使用第二种方法我发现它更干净,你可以更具体和更简单

