如果有人可以使用mvc 5向我发送链接或使用bootstrap模板站点地图显示如何实现自定义角色提供程序,我将不胜感激。
答案 0 :(得分:0)
实现自定义角色:
如果您尚未启用迁移
Enable-Migrations
,它会打开Configuration.cs,如果不打开,请在文件夹迁移中搜索; ,然后强>
在配置上搜索Seed并在种子内使用此代码:
context.Roles.AddOrUpdate(r => r.Name,
new IdentityRole { Name = "Role1" },
new IdentityRole { Name = "Role2" },
new IdentityRole { Name = "Role3" }
);
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
UserManager.AddToRole("Put User ID here", "Role1");
Add-Migration <name>
和Update-Database
要使用角色以便仅允许特定角色的访问:
在控制器上:
[Authorize(Roles="User")]
如果您想允许多个角色
[Authorize(Roles="User, Administrator")]
如果您需要某些条件
if (User.IsInRole("Admin"))
{
//execute x
} else {
//execute y
}
==编辑==
如何显示/隐藏菜单(更具体)
在MVC模板菜单上,在_Layout.cshtml页面上,在Views / Shared上。
我会在这里粘贴一个普通菜单和管理菜单的示例,其中包含更多选项:
<div class="navbar-collapse collapse">
@if (User.IsInRole("Admin"))
{
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Alerts", "Alerts", "Alerts")</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">BackOffice<span class="caret"></span></a>
<ul class="dropdown-menu">
<li>@Html.ActionLink("User Activity", "Index", "UserAccess")</li>
<li>@Html.ActionLink("Hospitals", "Index", "Hospitals")</li>
<li role="separator" class="divider"></li>
<li class="dropdown-submenu">
<a tabindex="-1" href="#">Management Tables</a>
<ul class="dropdown-menu">
<li>@Html.ActionLink("Exam Type", "Index", "Exams")</li>
<li>@Html.ActionLink("Medical Specialities", "Index", "MedicalSpecialities")</li>
</ul>
</li>
<li><a href="#">Separated link</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
}
else
{
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
<li>@Html.ActionLink("User Log", "Index", "UserAccess")</li>
</ul>
}
如您所见,@if (User.IsInRole("Admin")) { } else { }
是显示X菜单或Y菜单的条件。