User.IsInRole不工作。如何检查基于角色的授权?

时间:2014-07-09 12:49:44

标签: asp.net-mvc entity-framework identity

我正在使用带有EntityFramework 6的MVC 5.在“IdentityModel”中,我使用以下代码继承IdentityUser类:

public class ApplicationUser : IdentityUser
{
    [Display(Name="First Name")]
    [StringLength(50, ErrorMessage = "Length exceed")]
    public string FirstName { set; get; }

    [Display(Name = "Last Name")]
    [StringLength(50, ErrorMessage = "Length exceed")]
    public string LastName { set; get; }

}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
        this.Configuration.LazyLoadingEnabled = false;
    }


  protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {



        modelBuilder.Entity<IdentityUser>().HasKey(r => r.Id); 
        modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
        modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
        modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });


    }

我已使用以下代码将角色分配给“IdentityUser”:

UserManager.AddToRole(user.Id, "User");

我可以在“IdentityUserRole”表中看到已分配的角色,但在尝试使用

访问角色时
User.IsInRole("User");

它总是返回false。

在我的web.config中添加以下代码后,我得到“无法找到存储过程'dbo.aspnet_CheckSchemaVersion'。”这个错误。

<roleManager enabled="true" defaultProvider="SqlRoleProvider">
  <providers>
    <clear/> 
    <add name="SqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="DefaultConnection"  />
  </providers>
</roleManager>

我没有使用代码优先迁移。

2 个答案:

答案 0 :(得分:3)

User.IsInRole使用角色管理器的“旧”版本,而您的代码使用较新的Identity框架。而是使用新的UserManager(您似乎已经有了对象):

if (UserManager.IsInRole(user.Id, "Admin"))
{
    //...
}

答案 1 :(得分:0)

此版本适用于我:

if (UserManager.IsInRole(User.Identity.GetUserId(), "Admin"))
{
     Response.Write("IS IN ADMIN!");
}

如果你想在你的行动中使用具有角色名称的Authorize attribule,例如[授权(角色=&#34;管理员&#34;)],我建议你观看这个主题:Authorize attribute not working with roles

相关问题