实现一个基于用户角色的左侧栏菜单
- 创建一个ASP .NET Identity的模板项目。
- 修改模板项目的_Layout视图,实现左侧菜单。
- 创建一个Menu的class用存储菜单信息,并且创建ApplicationUserRole(让它继承IdentityRole),并且配置Menu和ApplicationUserRole之间多对多的关系。
- 可以点击链接去下载完整的项目,也可以直接查看下面的代码(只粘贴了部分)。
- 有时间我会慢慢加上注释的。
Menus
using Microsoft.AspNet.Identity.EntityFramework;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Xml.Serialization;
namespace DynamicLeftMenuBasedRoleMVCIdentityDemo.Models
{
[JsonObject(IsReference = true)]
public class Menus
{
[Key]
public int MainMenuId { get; set; }
public string MainMenuName { get; set; }
public string MainMenuUrl { get; set; }
public int? ParentMenuId { get; set; }
[ForeignKey("ParentMenuId")]
public List<Menus> SubMenus { get; set; }
public List<ApplicationUserRole> ApplicationUserRoles { get; set; }
}
}
IdentityModels
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Newtonsoft.Json;
namespace DynamicLeftMenuBasedRoleMVCIdentityDemo.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
ApplicationDbContext context = new ApplicationDbContext();
var roleManager = new RoleManager<ApplicationUserRole>(new RoleStore<ApplicationUserRole>(context));
var role = manager.GetRoles(userIdentity.GetUserId())[0].ToString();
var roleid = roleManager.Roles.Where(m => m.Name == role).Select(m => m.Id).FirstOrDefault();
var menulist = context.Menus.Include("ApplicationUserRoles").Include("SubMenus").Where(m => m.ApplicationUserRoles.Any(i => i.Id == roleid)).ToList();
var menulistjsonstring = JsonConvert.SerializeObject(menulist, Formatting.Indented,
new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
userIdentity.AddClaim(new Claim("menulist", menulistjsonstring));
// Add custom user claims here
return userIdentity;
}
}
publ