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) 这样的新方法来返回角色模型。
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; }
}