我为ApplicationUserRole添加了一个额外的属性,如下所示:
public class ApplicationUserRole : IdentityUserRole<int>
{
public string RoleAssigner { get; set; }
}
现在我要给一个用户分配一个角色,如下所示:
[HttpPost]
public ActionResult Create(UserRoleViewModel userRoleViewModel)
{
if (ModelState.IsValid)
{
using (var context = new ApplicationDbContext())
{
var userRole = new ApplicationUserRole
{
UserId = userRoleViewModel.UserId,
RoleId = userRoleViewModel.RoleId,
RoleAssigner = userRoleViewModel.RoleAssigner
};
context.ApplicationUserRoles.Add(userRole);
context.SaveChanges();
return RedirectToAction("Index");
}
}
return View(userRoleViewModel);
}
这个工作得很好!
在添加额外的"RoleAssigner"属性之前,我可以使用AddToRoles()方法为用户分配角色,如下所示:
[HttpPost]
public ActionResult Create(UserRoleViewModel userRoleViewModel)
{
if (ModelState.IsValid)
{
UserManager.AddToRoles(userRoleViewModel.Id, userRoleViewModel.RoleName);
return RedirectToAction("Index");
}
return View(userRoleViewModel);
}
我的问题是:添加了一个额外的属性,如"RoleAssigner",是否有任何方法来分配一个角色给用户使用AddToRoles()方法,这也将插入额外的"RoleAssigner"值"RoleAssigner"列在数据库中。
使用工作示例编辑:
我认为你可以通过在IdentityConfig创建一个扩展方法来做到这一点。我做了类似的事情,通过用户名或电话号码
查找用户在我能够理解你想要调用UserManager.AddToRoles(…)和填写新的角色属性
要做到这一点(与前面的示例类似),您需要扩展到user manager。你可以这样做:
public static class UserManagerExtens
{
public static IdentityResult AddToRole(this ApplicationUserManager userManager,string userId,string[] roles,string assigner)
{
try
{
ApplicationUserRole role = null;
using (ApplicationDbContext context = new ApplicationDbContext())
{
foreach (var item in roles)
{
role = new ApplicationUserRole();
role.UserId = userId;
role.RoleAssigner = assigner;
role.RoleId = item;
context.AspNetUserRoles.Add(role);
}
context.SaveChanges();
}
return new IdentityResult() { };
}
catch (Exception ex)
{
return new IdentityResult(ex.Message);
}
}
}
这是一个工作的例子,使用UserManager你可以调用它定义参数:
string[] roles = new string[] { /*your roles here*/ };
UserManager.AddToRole(/*UserIdHere*/, roles, /*assigerId here*/);
与此类似,您可以实现async或UserManager的其他方法
如果你在startup.cs中使用asp.net core应用程序,你应该注入适当的存储模型
services.AddIdentity<ApplicationUser, YOURROLEMODEL(ApplicationUserRole )>()
如果你正在使用asp.net应用程序应该有IdentityConfig.cs文件你应该实现你的UserStore这将让你的角色模型作为通用。您可以看到我已经创建了AppUserStore类,并且它将MyIdentityRole模型作为泛型类型。并更改ApplicationUserManager使用我的AppUserStore类。
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new AppUserStore(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,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
public class AppUserStore :
UserStore<ApplicationUser, MyIdentityRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUserStore<ApplicationUser>
{
public AppUserStore(DbContext context) : base(context)
{
}
}
public class MyIdentityRole : IdentityRole
{
public string MyProperty { get; set; }
}