1

I am using MVC 5 with EntityFramework 6. In "IdentityModel" I am inheriting IdentityUser class using following code:

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 });


    }

I have assigned roles to "IdentityUser" using the following code:

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

I can see assigned roles in "IdentityUserRole" table, but when trying to access the roles using

User.IsInRole("User");

It returns always false.

After adding following code in my web.config I get "Could not find stored procedure 'dbo.aspnet_CheckSchemaVersion'." this error.

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

I am not using code first migration.

tereško
  • 58,060
  • 25
  • 98
  • 150
Twix
  • 392
  • 1
  • 12
  • 38

2 Answers2

3

User.IsInRole uses the 'old' version of role manager whereas your code is using the newer Identity framework. Instead use the new UserManager (you seem to already have the object):

if (UserManager.IsInRole(user.Id, "Admin"))
{
    //...
}
DavidG
  • 113,891
  • 12
  • 217
  • 223
0

This version work for me:

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

If you want use Authorize attribule with role name like [Authorize(Roles = "Admin")] in your action, i recomend watch this topic:Authorize attribute not working with roles

Community
  • 1
  • 1
Anonimys
  • 596
  • 1
  • 5
  • 14