ASP.NET MVC 5 Customise Bootstrap navbar based on

2020-07-04 05:36发布

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.

Has anyone acheived this?

Where would be a starting point?

3条回答
Emotional °昔
2楼-- · 2020-07-04 06:12

Just wrap your links in:

@if (User.IsInRole("SomeRole"))
{
    ...
}
查看更多
beautiful°
3楼-- · 2020-07-04 06:17

You can use MvcSiteMap for 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.

I know it's frowned upon to post a links in answers but I found this blog post very 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:

<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.

查看更多
成全新的幸福
4楼-- · 2020-07-04 06:27

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

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

查看更多
登录 后发表回答