C# 基于角色的动态左侧菜单(使用ASP .NET Identity)

实现一个基于用户角色的左侧栏菜单

  1. 创建一个ASP .NET Identity的模板项目。
  2. 修改模板项目的_Layout视图,实现左侧菜单。
  3. 创建一个Menu的class用存储菜单信息,并且创建ApplicationUserRole(让它继承IdentityRole),并且配置Menu和ApplicationUserRole之间多对多的关系。
  4. 可以点击链接去下载完整的项目,也可以直接查看下面的代码(只粘贴了部分)。
  5. 有时间我会慢慢加上注释的。

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 SubMenus { get; set; }
        public List 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 GenerateUserIdentityAsync(UserManager 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(new RoleStore(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;
        }
    }
    public class ApplicationUserRole: IdentityRole
    {
        public List Menus { get; set; }
    }
    public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }
        public DbSet Menus { get; set; }
        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity()
                .HasMany(m=>m.Menus)
                .WithMany(m=>m.ApplicationUserRoles).Map(cs =>
                {
                    cs.MapLeftKey("RoleId");
                    cs.MapRightKey("MainMenuId");
                    cs.ToTable("AspNetRolesMenus");
                });
        }
    }
}

_LeftMenu.cshtml


@using Microsoft.AspNet.Identity
@using DynamicLeftMenuBasedRoleMVCIdentityDemo.Models

_Layout.cshtml




    
    
    @ViewBag.Title - My ASP.NET Application
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")


    @using Microsoft.AspNet.Identity
    
@if (Request.IsAuthenticated) { @Html.Partial("_LeftMenu") }
@RenderBody()
@Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false)

Startup.cs 

using DynamicLeftMenuBasedRoleMVCIdentityDemo.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;

[assembly: OwinStartupAttribute(typeof(DynamicLeftMenuBasedRoleMVCIdentityDemo.Startup))]
namespace DynamicLeftMenuBasedRoleMVCIdentityDemo
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app); 
            createRolesandUsers();
            createRolesandMenus();
        }
        private List getApplicationUserRoles(int i, List allroles)
        {
            List list = new List();
            if (i == 3)
            {
                list = allroles.ToList();
            }
            if (i == 2)
            {
                list = allroles.Take(2).ToList();
            }
            if (i == 1)
            {
                list =allroles.Take(1).ToList();
            }
            return list;
        }
        private int createMenus(int? i,int? j,int? k,List allroles, ApplicationDbContext context,int? parenti,int? parentj)
        {
            Menus menu = new Menus {MainMenuName = "Menu" };
            if (i!= null)
            {
                menu.MainMenuName += "_" + i.ToString();
                menu.ParentMenuId = null;
            }
            if (j!= null)
            {
                menu.MainMenuName += "_" + j.ToString();
                menu.ParentMenuId = Int32.Parse(parenti.ToString());
            }
            if (k != null)
            {
                menu.MainMenuName += "_" + k.ToString();
                menu.ParentMenuId = Int32.Parse(parentj.ToString());
            }
            menu.ApplicationUserRoles = getApplicationUserRoles(Int32.Parse(i.ToString()), allroles);
            context.Menus.Add(menu);
            context.SaveChanges();
            return menu.MainMenuId;
        }
        private void createRolesandMenus()
        {
            ApplicationDbContext context = new ApplicationDbContext();
            if (context.Menus.ToList().Count() == 0)
            {
                var roleManager = new RoleManager(new RoleStore(context));
                var allroles = roleManager.Roles.ToList();
                for (int i = 1; i < 4; i++)
                {
                    var parenti=createMenus(i, null, null, allroles, context,null,null);
                    Random random = new Random();
                    var index1 = random.Next(1, 4);
                    var index2 = random.Next(1, 5);
                    for (int j = 1; j < index1; j++)
                    {
                        var parentj=createMenus(i, j, null, allroles, context, parenti, null);
                        for (int k = 1; k < index2; k++)
                        {
                            createMenus(i, j, k, allroles, context, parenti, parentj);
                        }
                    }
                }
            }
        }
        // In this method we will create default User roles and Admin user for login    
        private void createRolesandUsers()
        {
            ApplicationDbContext context = new ApplicationDbContext();
            var roleManager = new RoleManager(new RoleStore(context));
            var UserManager = new UserManager(new UserStore(context));
            // In Startup iam creating first Admin Role and creating a default Admin User     
            if (!roleManager.RoleExists("Admin"))
            {
                // first we create Admin rool    
                var role = new ApplicationUserRole();
                role.Name = "Admin";
                roleManager.Create(role);
                //Here we create a Admin super user who will maintain the website                   
                var user = new ApplicationUser();
                user.UserName = "test";
                user.Email = "[email protected]";
                string userPWD = "12345ABCDEq@";
                var chkUser = UserManager.Create(user, userPWD);
                //Add default User to Role Admin    
                if (chkUser.Succeeded)
                {
                    var result1 = UserManager.AddToRole(user.Id, "Admin");
                }
            }
            // creating Creating Manager role     
            if (!roleManager.RoleExists("Manager"))
            {
                var role = new ApplicationUserRole();
                role.Name = "Manager";
                roleManager.Create(role);
                var user = new ApplicationUser();
                user.UserName = "testManager";
                user.Email = "[email protected]";
                string userPWD = "12345ABCDEq@";
                var chkUser = UserManager.Create(user, userPWD);
                //Add default User to Employee role  
                if (chkUser.Succeeded)
                {
                    var result1 = UserManager.AddToRole(user.Id, "Manager");
                }
            }
            // creating Creating Employee role     
            if (!roleManager.RoleExists("Employee"))
            {
                var role = new ApplicationUserRole();
                role.Name = "Employee";
                roleManager.Create(role);
                var user = new ApplicationUser();
                user.UserName = "testEmployee";
                user.Email = "[email protected]";
                string userPWD = "12345ABCDEq@";
                var chkUser = UserManager.Create(user, userPWD);
                //Add default User to Employee role     
                if (chkUser.Succeeded)
                {
                    var result1 = UserManager.AddToRole(user.Id, "Employee");
                }
            }
        }
    }
}

IdentityExtensions.cs

using DynamicLeftMenuBasedRoleMVCIdentityDemo.Models;
using Microsoft.AspNet.Identity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Web;

namespace DynamicLeftMenuBasedRoleMVCIdentityDemo
{
    public static class IdentityExtensions
    {
        public static List GetMenusList(this IIdentity identity)
        {
            if (identity == null)
            {
                throw new ArgumentNullException("identity");
            }
            var claimsidentity = identity as ClaimsIdentity;
            List menulist = new List();
            if (claimsidentity != null)
            {
                var value = claimsidentity.FindFirstValue("menulist");
                menulist = String.IsNullOrEmpty(value)?null: JsonConvert.DeserializeObject>(value);
            }
            return menulist;
        }
    }
}

效果图:

C# 基于角色的动态左侧菜单(使用ASP .NET Identity)_第1张图片

 

你可能感兴趣的:(asp.net,sql,bootstrap)