2015-07-17 2 views
0

Базовая функциональность для GetRolesAsync (TKey USERID) следующаяПереопределение базовую функциональность UserManager.GetRolesAsync (TKey USERID)

 public virtual async Task<IList<string>> GetRolesAsync(TKey userId) 
    { 
     ThrowIfDisposed(); 
     var userRoleStore = GetUserRoleStore(); 
     var user = await FindByIdAsync(userId).WithCurrentCulture(); 
     if (user == null) 
     { 
      throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound, 
       userId)); 
     } 
     return await userRoleStore.GetRolesAsync(user).WithCurrentCulture(); 
    } 

Кто-нибудь знает, как переопределить эту функцию в производном классе UserManager или даже предоставить новый метод, например GetModelRolesAsync (string userId), чтобы вернуть roleModel.

public class ApplicationUserManager : UserManager<ApplicationUser> 
{ 
    public ApplicationUserManager(IUserStore<ApplicationUser> store) 
     : base(store) 
    { 
    } 

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    { 
     var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>())); 
     // Configure validation logic for usernames 
     manager.UserValidator = new UserValidator<ApplicationUser>(manager) 
     { 
      AllowOnlyAlphanumericUserNames = false, 
      RequireUniqueEmail = true 
     }; 
     // Configure validation logic for passwords 
     manager.PasswordValidator = new PasswordValidator 
     { 
      RequiredLength = 6, 
      RequireNonLetterOrDigit = true, 
      RequireDigit = true, 
      RequireLowercase = true, 
      RequireUppercase = true, 
     }; 
     var dataProtectionProvider = options.DataProtectionProvider; 
     if (dataProtectionProvider != null) 
     { 
      manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity")); 
     } 
     return manager; 
    } 

    public override async Task<IList<RoleModel>> GetRolesAsync(string userId) 
    { 
     // Need code here to return a RoleModel that includes the ID 
     // as well as the role name, so a complex object instead of just 
     // a list of strings 


    } 
} 


public class RoleModel 
{ 
    public string Id { get; set; } 
    public string Name { get; set; } 
} 

ответ

1

Asp.Net Идентичность Entity Framework библиотека предоставляет Role Model Удостоверение из коробки под названием IdentityRole. Вы можете использовать это в сочетании с предоставленным RoleManager Class, чтобы вернуть модель IdentityRole.

Вы должны будете предоставить свою собственную функцию, но интерфейс для Task<IList<string>> GetRolesAsync(TKey userId) установлен в базовом классе для возврата только строк.

Вот пример:

public class ApplicationUserManager : UserManager<ApplicationUser> 
{ 
    private RoleManager<IdentityRole> _roleManager; 

    public ApplicationUserManager(IUserStore<ApplicationUser> store) 
     : base(store) 
    { 
     _roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>()); 
    } 

    public async Task<IList<IdentityRole>> GetModelRolesAsync(string userId) 
    { 
     IList<string> roleNames = await base.GetRolesAsync(userId); 

     var identityRoles = new List<IdentityRole>(); 
     foreach (var roleName in roleNames) 
     { 
      IdentityRole role = await _roleManager.FindByNameAsync(roleName); 
      identityRoles.Add(role); 
     } 

     return identityRoles; 
    }  
} 

Вы можете настроить систему для использования ASP.NET встроенный в систему впрыска зависимостей для RoleManager, как показано here.

+0

Отлично! Спасибо, просто не мог соединить точки на этом! – DRobertE

Смежные вопросы