2014-02-27 68 views
5

我正在使用ASPNet Identity在我的Web應用程序中實現安全性。擴展IdentityRole和IdentityUser

有一個需求,我需要擴展IdentityRole和IdentityUser。

這裏是我的代碼來擴展IdentityUser。

public class ApplicationUser : IdentityUser 
{ 
    public virtual User User { get; set; } 
} 

public class ApplicationDbContext : IdentityDbContext<ApplicationUser> 
{ 
    public ApplicationDbContext() 
     : base("name=CoreContext") 
    { 
    } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     base.OnModelCreating(modelBuilder); 

     modelBuilder.Entity<IdentityUser>() 
      .ToTable("AspNetUsers"); 
     modelBuilder.Entity<ApplicationUser>() 
      .ToTable("AspNetUsers"); 
    } 
} 

我唯一的問題是IdentityRole

+0

而你的問題/問題是......究竟是什麼?請更新您的問題一些更多的細節。 –

+0

我的問題是我無法擴展IdentityRole。 –

+0

@RamonCruz - 誰說你不能擴展IdentityRole? –

回答

3

爲了擴大用戶,更新您ApplicationUser類(位於IdentityModels.cs)以

public class ApplicationUser : IdentityUser 
{ 
    public async Task<ClaimsIdentity> 
     GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) 
    { 
     var userIdentity = await manager 
      .CreateIdentityAsync(this, 
       DefaultAuthenticationTypes.ApplicationCookie); 
     return userIdentity; 
    } 

    public string Address { get; set; } 
    public string City { get; set; } 
    public string State { get; set; } 

    // Use a sensible display name for views: 
    [Display(Name = "Postal Code")] 
    public string PostalCode { get; set; } 

} 

來擴展角色,創建一類ApplicationRole.cs

public class ApplicationRole : IdentityRole 
{ 
    public ApplicationRole() : base() { } 
    public ApplicationRole(string name) : base(name) { } 
    public string Description { get; set; } 
} 

,並添加內IdentityConfig.cs文件中的類:

public class ApplicationRoleManager : RoleManager<ApplicationRole> 
{ 
    public ApplicationRoleManager(
     IRoleStore<ApplicationRole,string> roleStore) 
     : base(roleStore) 
    { 
    } 
    public static ApplicationRoleManager Create(
     IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context) 
    { 
     return new ApplicationRoleManager(
      new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>())); 
    } 
} 

現在清除舊的數據庫,運行應用程序並註冊一個用戶。它將在AspNetUsers表中創建另外3個字段(地址,城市,州)和一個字段(描述)到AspNetRoles表中。而已。

欲瞭解更多信息,請訪問網站: Extending Identity Role

+1

嗨,你有沒有暗示多租戶,我有問題擴展屬性[角色](http://stackoverflow.com/q/43269854/6085193) – transformer