ASP.NET MVC 异常'The Role Manager feature has not been enabled'



我正在尝试制作一个ASP.net MVC网站。我在Startup.cs文件中设置了如下角色:

private void CreateRolesAndUsers()
{
ApplicationDbContext context = new ApplicationDbContext();
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
if (!roleManager.RoleExists("SuperAdmin"))
{
// first we create Admin role   
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
role.Name = "SuperAdmin";
roleManager.Create(role);
//Here we create a Admin super user who will maintain the website
var user = new ApplicationUser();
user.UserName = "SuperAdmin";
user.Email = "SuperAdmin@SU.com";
string userPWD = "Password1";
var chkUser = UserManager.Create(user, userPWD);
//Add default User to Role Admin   
if (chkUser.Succeeded)
{
var result1 = UserManager.AddToRole(user.Id, "SuperAdmin");
}
}
}

我已经验证了上面的代码成功地将角色添加到数据库中,当我尝试角色时,我第一次注意到角色不起作用。IsUserInRole(User.Identity.Name,"SuperAdmin"(

我试图控制哪些角色在视图中看到某些内容,并得到一个异常:

System.Configuration.Provider.ProviderException:"尚未启用角色管理器功能。">

当我试图调用.cs.html文件中的以下行时:@Roles.GetRolesForUser((;

我在Web.config中查找了在哪里启用roleManager,但找不到,如果我将其添加到system.Web部分中,它就不起作用

EDIT:每当使用IsUserInRole时,在以下代码中添加(>roleManager enabled="true"<(会产生另一个未处理的异常:"System.Web.HttpException:无法连接到SQL Server数据库。">

<system.web>
<authentication mode="None"/>
<compilation debug="true" targetFramework="4.7"/>
<httpRuntime targetFramework="4.7"/>
</system.web>

我想我可能只是缺少了一个依赖项或某个初始化器,但没有任何线索,类似问题中的其他解决方案都不起作用。

您可以通过读取以下位置的布尔属性来完成此操作:

System.Web.Security.Roles.Enabled这是从web.config中的roleManager元素的enabled属性直接读取的:

<configuration>
<system.web>
<roleManager enabled="true" />
</system.web>
</configuration>

有关详细信息,请查看此MSDN示例:https://msdn.microsoft.com/en-us/library/aa354509(v=vs.110(.aspx

相关内容