ASP.NET Identity “角色-权限”管理 6
1.1. Role-Permission
UserRole是User与Role的关联表,代码见User-Role分析。参考可得Role-Permission的设计,代码图如下,RolePermission是Role与Permission的关联表,保存着RoleId与PermissionId。
1.1.1. 新建RolePermission
在IdentityModels.cs中增加ApplicationRolePermission类。
public class ApplicationRolePermission { public virtual string RoleId { get; set; } public virtual string PermisssionId { get; set; } } |
1.1.2. 添加RolePermission列表
向ApplicationRole中添加RolePermission列表。
public class ApplicationRole : IdentityRole { public ApplicationRole() : base() { Permissions = new List<ApplicationRolePermission>(); } public ApplicationRole(string roleName) : this() { base.Name = roleName; }
[Display(Name = "角色描述")] public string Description { get; set; } /// <summary> /// 权限列表 /// </summary> public ICollection<ApplicationRolePermission> Permissions { get; set; } } |
向ApplicationPermission中添加RolePermission列表。
public class ApplicationPermission { public ApplicationPermission() { Id = Guid.NewGuid().ToString(); Roles = new List<ApplicationRolePermission>(); } /// <summary> /// 主键 /// </summary> public string Id { get; set; } /// <summary> /// 控制器名 /// </summary> public string Controller { get; set; } /// <summary> /// 方法名 /// </summary> public string Action { get; set; } /// <summary> /// 参数字符串 /// </summary> public string Params { get; set; } /// <summary> /// 功能描述 /// </summary> public string Description { get; set; } /// <summary> /// 角色列表 /// </summary> public ICollection<ApplicationRolePermission> Roles { get; set; } } |
1.1.3. 配置Role-Permission多对多关系
重写ApplicationDbContext的OnModelCreating,配置Role-RolePermission和Permission-RolePermission的1对多关系。
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection") { // 在第一次启动网站时初始化数据库添加管理员用户凭据和admin 角色到数据库 Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer()); }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
if (modelBuilder == null) { throw new ArgumentNullException("modelBuilder"); } //配置permission与rolePermission的1对多关系 EntityTypeConfiguration<ApplicationPermission> configuration = modelBuilder.Entity<ApplicationPermission>().ToTable("ApplicationPermissions"); configuration.HasMany<ApplicationRolePermission>(u => u.Roles).WithRequired().HasForeignKey(ur => ur.PermisssionId); //配置role与persmission的映射表RolePermission的键 modelBuilder.Entity<ApplicationRolePermission>().HasKey(r => new { PermisssionId = r.PermisssionId, RoleId = r.RoleId }).ToTable("ApplicationRolePermissions"); //配置role与RolePermission的1对多关系 EntityTypeConfiguration<ApplicationRole> configuration2 = modelBuilder.Entity<ApplicationRole>(); configuration2.HasMany<ApplicationRolePermission>(r => r.Permissions).WithRequired().HasForeignKey(ur => ur.RoleId);
base.OnModelCreating(modelBuilder); }
public static ApplicationDbContext Create() { return new ApplicationDbContext(); }
public new IDbSet<ApplicationRole> Roles { get; set; } public virtual IDbSet<ApplicationPermission> Permissions { get; set; }
} |
注意:因为需要的类型是ApplicationRole,所以覆盖了父类中属性Roles定义。
1.1.4. 建立ViewModel
向PermissionViewModel中添加RoleId、RoleName属性。
public class PermissionViewModel { /// <summary> /// 主键 /// </summary> [Display(Name = "权限ID")] public string Id { get; set; } /// <summary> /// 控制器名 /// </summary> [Required(AllowEmptyStrings = false)] [Display(Name = "控制器名")] public string Controller { get; set; } /// <summary> /// 方法名 /// </summary> [Required(AllowEmptyStrings = false)] [Display(Name = "方法名")] public string Action { get; set; } /// <summary> /// 功能描述 /// </summary> [Required(AllowEmptyStrings = true)] [Display(Name = "功能描述")] public string Description { get; set; } [Display(Name = "选择")] public bool Selected { get; set; } [Display(Name = "角色ID")] public string RoleId { get; set; } [Display(Name = "角色名")] public string RoleName { get; set; }
} |
1.1.5. 建立Controller
Role-Permission管理无需编辑功能,比Permission管理多了一个传入参数RoleId,新建RolePermissionsController.cs,添加相应的MVC部件,这里不再累述可参考前面章节。
Index,使用AutoMapper完成对象映射。
public async Task<ActionResult> Index(string roleId) { //取role列表 var roles = _roleManager.Roles.ToList(); //roleId是否为空 if (roleId == null) { //取第一个role的id roleId = roles.FirstOrDefault().Id; } //放入viewbag,设置默认值 ViewBag.RoleID = new SelectList(roles, "ID", "Description", roleId); //取角色权限列表 var permissions = await _roleManager.GetRolePermissionsAsync(roleId); //创建ViewModel var permissionViews = new List<PermissionViewModel>();
var map = Mapper.CreateMap<ApplicationPermission, PermissionViewModel>(); permissions.Each(t => { var view = Mapper.Map<PermissionViewModel>(t); view.RoleID = roleId; permissionViews.Add(view); }); //排序 permissionViews.Sort(new PermissionViewModelComparer()); return View(permissionViews); } |
HttpPost方法的Create。
// POST: RolePermissions/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Create(string roleId, IEnumerable<PermissionViewModel> data) { if (string.IsNullOrWhiteSpace(roleId)) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } //添加Permission foreach (var item in data) { var permission = new ApplicationRolePermission { RoleId = roleId, PermissionId = item.Id }; //方法1,用set<>().Add() _db.Set<ApplicationRolePermission>().Add(permission); } //保存; var records = await _db.SaveChangesAsync();
//return RedirectToAction("Index", new { roleId = roleId }); //返回消息 Dictionary<string, bool> response = new Dictionary<string, bool>(); response.Add("Success", true); return new JsonResult { Data = response }; } |
1.1.6. 运行效果
Index
Create
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。