用户、角色的权限管理

一、VS后台操作API

    1、VS需要安装的包

 

     2、在appsettings.json 需要配置 连接数据库,JWT

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "MsSqlServer": "Data Source=.;Initial Catalog=RBACDBSLQ;User ID=sa;pwd=123456"
  },
  "JwtSettings": {
    "Issuer": "JwtAuthDemo",
    "SignKey": "134oskqkflps63055" //固定 长度大于十六位以上的字符串
  }
}

    3、在Startup.cs进行配置

using BaWei.RBACExam.Config;
using BaWei.RBACExam.DapperRepository.Repository;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaWei.RBACExam.AdminWebApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "BaWei.RBACExam.AdminWebApi", Version = "v1" });
                #region  开启Swagger认证
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {

                    Description = "在下框中输入请求头中需要添加Jwt授权Token:Bearer Token",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme,
                                Id = "Bearer"
                            }
                        },
                        new string[] { }
                    }
                });
                #endregion
            });
            //跨域:
            services.AddCors(option =>
            {
                option.AddDefaultPolicy(p => {
                    p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
                });
            });


            //JWT
            services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        // 當驗證失敗時,回應標頭會包含 WWW-Authenticate 標頭,這裡會顯示失敗的詳細錯誤原因
        options.IncludeErrorDetails = true; // 預設值為 true,有時會特別關閉

        options.TokenValidationParameters = new TokenValidationParameters
        {
            // 透過這項宣告,就可以從 "sub" 取值並設定給 User.Identity.Name
            NameClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier",
            // 透過這項宣告,就可以從 "roles" 取值,並可讓 [Authorize] 判斷角色
            RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role",

            // 一般我們都會驗證 Issuer
            ValidateIssuer = true,
            ValidIssuer = Configuration.GetValue<string>("JwtSettings:Issuer"),

            // 通常不太需要驗證 Audience
            ValidateAudience = false,
            //ValidAudience = "JwtAuthDemo", // 不驗證就不需要填寫

            // 一般我們都會驗證 Token 的有效期間
            ValidateLifetime = true,

            // 如果 Token 中包含 key 才需要驗證,一般都只有簽章而已
            ValidateIssuerSigningKey = false,

            // "1234567890123456" 應該從 IConfiguration 取得
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetValue<string>("JwtSettings:SignKey")))
        };
    });


            //原样输出
            services.AddControllers()
            .AddNewtonsoftJson(options => {
                // 忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                // 不使用驼峰
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                // 设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                // 如字段为 null 值,该字段不会返回到前端
                // options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            });
            //注入
            services.AddTransient<MemuRepository>();
            services.AddTransient<Repostitory>();
            services.AddTransient<AdminRepostory>();
            services.AddTransient<RoleRepostory>();
            services.AddSingleton<JwtHelpers>();
        }


        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BaWei.RBACExam.AdminWebApi v1"));
            }

            app.UseRouting();

            app.UseCors();
            //验证
            app.UseAuthentication();
            //权限
            app.UseAuthorization();

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
Path.Combine(env.ContentRootPath, "Images")),
                RequestPath = "/StaticFiles"
            });


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

    4、SQL

 

create database RBACDBSLQ
go
use RBACDBSLQ
go
--菜单
create table SysMenu
(
  MenuId Nvarchar(40) primary key not null,
  MenuName Nvarchar(64) not null,
  ParentMenuId Nvarchar(40),
  Level int not null,
  Url Nvarchar(256),
  Type int not null,
  Icon Nvarchar(128) not null,
  OrderIndex int not null,
  Deleted bit not null,
  CreateTime datetime not null,
  CreatedBy bigint not null,
  UpdateTime datetime not null,
  UpdateBy bigint not null,
)
go
--角色
create table SysRole
(
  RoleId bigint primary key not null,
  RoleName Nvarchar(25) not null,
  RoleDesc Nvarchar(128) not null,
  Deleted bit not null,
  CreatedTime datetime not null,
  CreatedBy bigint not null,
  UpdatedTime datetime not null,
  UpdateBy bigint not null,
)
go
--角色菜单
create table SysRoleMenuRelation
(
  RoleId bigint primary key not null,
  MenuId Nvarchar(40) not null,
  State int not null,
  Deleted bit not null,
  CreatedTime datetime not null,
  CreatedBy bigint not null,
  UpdatedTime dateTime not null,
  UpdatedBy bigint not null
)
go
--用户
create table SysUser
(
  UserId bigint primary key not null,
  NickName Nvarchar(30) not null,
  PassWord Nvarchar(512) not null,
  Email Nvarchar(128) not null,
  Sex int not null,
  State int not null,
  Deleted bit not null,
  CreatedTime datetime not null,
  CreatedBy bigint not null,
  UpdatedTime datetime not null,
  UpdatedBy bigint not null,
  DeptIds Nvarchar(Max) null
)
go
--用户权限
create table SysUserRoleRelation
(
  UserId bigint primary key not null,
  RoleId bigint not null,
  State int,
  Deleted bit,
  CreatedTime datetime,
  CreatedBy bigint,
  UpdatedTime datetime,
  UpdateBy bigint
)



select * from SysMenu
insert SysMenu values('M1','系统管理','','1','','1','el-icon-setting','1','','2021-11-03','','2021-11-03','')
insert SysMenu values('M101','用户管理','M1','2','','1','el-icon-','1','','2021-11-03','','2021-11-03','')
insert SysMenu values('M102','菜单管理','M1','2','','1','el-icon-','2','','2021-11-03','','2021-11-03','')
insert SysMenu values('M103','角色管理','M1','2','','1','el-icon-','2','','2021-11-03','','2021-11-03','')
insert SysMenu values('M104','部门管理','M1','2','','1','el-icon-','2','','2021-11-03','','2021-11-03','')

select * from SysUser
insert into SysUser values('1001','华茂','111','huamao@163.com','1',0,1,'2021-11-10','','2021-11-10','','')
insert into SysUser values('1002','孙凯','111','sunkai@163.com','1',0,1,'2021-11-10','','2021-11-10','','')
insert into SysUser values('1003','孙观','111','sunguan@163.com','1',0,1,'2021-11-10','','2021-11-10','','')
insert into SysUser values('1004','潘才','111','pancai@163.com','1',0,1,'2021-11-10','','2021-11-10','','')
insert into SysUser values('1005','苏牧','111','sumu@163.com','1',0,1,'2021-11-10','','2021-11-10','','')

select * from SysRole where 1=1
insert into SysRole values('101','普通成员','简介',1,'2021-11-10','','2021-11-10','')
insert into SysRole values('102','管理员','简介',1,'2021-11-10','','2021-11-10','')
insert into SysRole values('103','超级管理员','简介',1,'2021-11-10','','2021-11-10','')

 

 

 

二、Dal层方法使用

    1、主要的数据访问

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BaWei.RBACExam.Model.Dto.Response.ResponseDtoModel.MenuDtoModel;
using BaWei.RBACExam.Model.SysDomain;
using Dapper;
using Microsoft.Extensions.Configuration;

namespace BaWei.RBACExam.DapperRepository.Repository
{
    public class MemuRepository
    {
        private readonly IConfiguration _configuration;
        public MemuRepository(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 导航菜单全部显示
        /// </summary>
        /// <returns></returns>
        public List<MenuResponse> GetMenus()
        {
            using(IDbConnection conn=new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))
            {
                var list = conn.Query<SysMenu>("select * from SysMenu").ToList();
                return GetMenuResponses(list);
            }
        }

        public List<MenuResponse>GetMenuResponses(List<SysMenu> sysMenus,string parentMenuId="")
        {
            return sysMenus.Where(p => p.Type == Config.SysConstants.MenuType.Menu && p.ParentMenuId==parentMenuId && p.Deleted==false).Select(p=>new MenuResponse 
            { 
                Icon=p.Icon,
                Type=p.Type,
                Level=p.Level,
                MenuId = p.MenuId,
                MenuName=p.MenuName,
                OrderIndex=p.OrderIndex,
                ParentMenuId=parentMenuId,
                Url=p.Url,
                ChildMenus = GetMenuResponses(sysMenus,p.MenuId)

            }).ToList();
        }

        /// <summary>
        /// 显示
        /// </summary>
        /// <param name="totalCount"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="sname"></param>
        /// <param name="youx"></param>
        /// <returns></returns>
        public List<SysUser> GetAllShow(out int totalCount,string sname,string youx, int pageindex = 1, int pagesize = 3)
        {
            using (IDbConnection conn = new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))
            {
                var sql = "select * from SysUser where 1=1";
                if(!string.IsNullOrEmpty(sname))
                {
                    sql += " and NickName like '%"+ sname +"%'";
                }
                if(!string.IsNullOrEmpty(youx))
                {
                    sql += " and Email like '%" + youx + "%'";
                }

                var list = conn.Query<SysUser>(sql);
                totalCount = list.Count();
                list =list.OrderBy(p => p.UserId).Skip((pageindex - 1) * pagesize).Take(pagesize).ToList();
               
                return list.ToList();

            }
           
        }
        /// <summary>
        /// 单删
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DanShan(int id)
        {
            using(IDbConnection conn=new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))
            {
                conn.Query<SysUser>($"delete from SysUser where UserId='{id}'");
            }
            return 1;
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public int PostAddUser(SysUser user)
        {
            using(IDbConnection conn=new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))
            {
               string sql=$"insert into SysUser values('{user.UserId}','{user.NickName}','{user.PassWord}','{user.Email}','{user.Sex}','0','1','{user.CreatedTime}','0','{user.UpdatedTime}','0','')";
                int list = conn.Execute(sql);
                return list;
            }
        }

        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public int PostUpdate(SysUser user)
        {
            using(IDbConnection conn=new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))
            {
                string sql = $"update SysUser set  NickName='{user.NickName}',PassWord='{user.PassWord}',Email='{user.Email}',Sex='{user.Sex}',CreatedTime='{user.CreatedTime}',UpdatedTime='{user.UpdatedTime}' where UserId='{user.UserId}'";
                var list = conn.Execute(sql);
                return list;
            }
        }



        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <returns></returns>
        public PageResponse<SysRole> GetRoleList()
        {
            var result = new PageResponse<SysRole>();
            using(var conn=new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))
            {
                result.PageData = conn.Query<SysRole>("select * from SysRole where Deleted=1").ToList();
                return result;
            }
        }

        /// <summary>
        /// 角色权限的显示
        /// </summary>
        /// <returns></returns>
       public List<SysRole> AllShowShuJu()
        {
            using (var conn = new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))
            {
                string sql = "select* from SysRole where 1 = 1";
                var list = conn.Query<SysRole>(sql).ToList();
                return list;
            }
        }
        /// <summary>
        /// 角色权限的添加
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public int AddJiaoRole(SysRole role)
        {
            using (var conn = new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))
            {
                string sql = $"insert into SysRole values('{role.RoleId}','{role.RoleName}','{role.RoleDesc}',1,GETDATE(),0,GETDATE(),0)";
                var list = conn.Execute(sql);
                return list;
            }
        }

        /// <summary>
        /// 角色权限的删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int RoleDelete(long roleId)
        {
            using (var conn = new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))
            {
                var list = conn.Execute($"Delete SysRole where RoleId={roleId}");
                return list;

            }
        }

 


    }
}

    2、管理的数据访问

using BaWei.RBACExam.Model.Dto.Response.ResponseDtoModel.MenuDtoModel;
using BaWei.RBACExam.Model.SysDomain;
using Dapper;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaWei.RBACExam.DapperRepository.Repository
{
   public class AdminRepostory
    {
        private readonly IConfiguration _configuration;
        public AdminRepostory(IConfiguration configuration)
        {
            _configuration = configuration;
        }


        /// <summary>
        /// 显示管理
        /// </summary>
        /// <returns></returns>
        public List<MenuResponse> GetMenuXiTOng(string sname,bool? state)
        {
            using (IDbConnection conn = new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))
            {
                string sql = "select * from SysMenu where 1=1 ";
                if(!string.IsNullOrEmpty(sname))
                {
                    sql += " and MenuId like '%" + sname + "%'";
                }
                if(state!=null)
                {
                    sql += " and Deleted = " + state + "";
                }

                var list = conn.Query<SysMenu>(sql).ToList();
                return GetMenuResponsesf(list);
            }
        }

        public List<MenuResponse> GetMenuResponsesf(List<SysMenu> sysMenus, string parentMenuId = "")
        {
            return sysMenus.Where(p => p.Type == Config.SysConstants.MenuType.Menu && p.ParentMenuId == parentMenuId && p.Deleted == false).Select(p => new MenuResponse
            {
                Icon = p.Icon,
                Type = p.Type,
                Level = p.Level,
                MenuId = p.MenuId,
                MenuName = p.MenuName,
                OrderIndex = p.OrderIndex,
                ParentMenuId = parentMenuId,
                Url = p.Url,
                ChildMenus = GetMenuResponsesf(sysMenus, p.MenuId)

            }).ToList();
        }

        private List<MenuResponse> GetMenuResponses(List<SysMenu> sysMenus, string menuId)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 单删管理
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DeletMen(string menuId)
        {
            using(IDbConnection conn=new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))
            { 
                string sql= $"delete from SysMenu where MenuId = '{menuId}'";
               var list=  conn.Execute(sql);
                return list;
            }
        }
    }
}

    3、分配角色

using BaWei.RBACExam.Model.Dto.RequestParamsDto;
using BaWei.RBACExam.Model.Dto.Response.ResponseDtoModel.MenuDtoModel;
using BaWei.RBACExam.Model.SysDomain;
using Dapper;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaWei.RBACExam.DapperRepository.Repository
{
    public class Repostitory
    {

        private readonly IConfiguration _configuration;
        public Repostitory(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 添加 分配的角色 
        /// </summary>
        /// <returns></returns>
        public ResponseModel<bool> PostAllocation(SysUserRoleRelations sysUser)
        {
            var result = new ResponseModel<bool>();
            using (var conn = new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))
            {
                conn.Open();//打开连接
                using (var begin = conn.BeginTransaction())
                {
                    try
                    {
                        var count = 0;
                        foreach(var item in sysUser.RoleIds.Split(','))
                        {
                            count += conn.Execute($"insert into SysUserRoleRelation(UserId,RoleId) values('{sysUser.UserId}','{item}')", null, begin); 
                        }
                        if(count>0)
                        {
                            begin.Commit();
                            return result.Succeed(true);
                        }
                        else
                        {
                            begin.Rollback();
                        }
                    }
                    catch (Exception ex)
                    {
                        begin.Rollback();

                        throw ex;
                    }
                }

            }
            return result.Fail("添加失败");
        }


        /// <summary>
        /// 根据用户ID获取所有角色ID
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public PageResponse<SysUserRoleRelation> GetUserId (long userid)
        {
            var result = new PageResponse<SysUserRoleRelation>();
            using(var conn=new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))

            {
                var sql = $"select * from SysUserRoleRelation where UserId='{userid}'";
                result.PageData = conn.Query<SysUserRoleRelation>(sql).ToList();
            }
            return result;

        }

    }
}

    4、角色的权限

using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data;
using System.Data.SqlClient;
using BaWei.RBACExam.Model;
using BaWei.RBACExam.Model.Dto.RequestParamsDto;
using BaWei.RBACExam.Model.Dto.Response.ResponseDtoModel.MenuDtoModel;
using BaWei.RBACExam.Model.SysDomain;

namespace BaWei.RBACExam.DapperRepository.Repository
{
    public class RoleRepostory
    {

        private readonly IConfiguration _configuration;
        public RoleRepostory(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 角色 权限 添加
        /// </summary>
        /// <param name="sysRole"></param>
        /// <returns></returns>
        public int PostRole(SysRoleMenuRelations sysRole)
        {
           using(var conn=new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))
            {
                //var kk = conn.Execute($"delete SysRoleMenuRelation  where RoleId='{sysRole.RoleIds}'");
                var list = 0;
                
               // if(kk>0)
               // {
                    foreach (var item in sysRole.MenuIds.Split(','))
                    {
                        list = conn.Execute($"insert SysRoleMenuRelation values('{sysRole.RoleIds}','{item}',0,1,GetDate(),0,GetDate(),0)");
                    }
               // }
                return list;
            }
        }
        /// <summary>
        /// 查看权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public List<SysRoleMenuRelation> EidBianJi(long roleId)
        {
            using (var conn = new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))
            {
                string sql = $"select * from SysRoleMenuRelation where RoleId='{roleId}'";
                var list = conn.Query<SysRoleMenuRelation>(sql).ToList();
                return list;
            }
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="snam"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public ResponseModel<SysUser> Register(string snam,string pwd)
        {
            ResponseModel<SysUser> responseModel = new ResponseModel<SysUser>();

            using (var conn = new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))
            {
                var list = conn.Query<SysUser>($"select * from SysUser where NickName='{snam}' and  PassWord='{pwd}'").FirstOrDefault();

                if(list == null)
                {
                    return responseModel.Fail(ResponseCode.LoginFail, "登录失败");
                }
                else
                {
                    return responseModel.Succeed(list);
                }
                //var list = conn.Query<SysUser>(sql).FirstOrDefault();
                //return list;


            }
        }

        /// <summary>
        /// 根据登录人进行显示
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<MenuResponse> JurisdictionShow(long? userId)
        {
            using (IDbConnection conn = new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))
            {
                var sql = $"select  c.MenuId,c.MenuName,c.Icon,c.ParentMenuId,c.Level,c.Url,c.Type  from SysUserRoleRelation a join SysRoleMenuRelation b on a.RoleId=b.RoleId join SysMenu c on b.MenuId=c.MenuId where 1=1";
                if(userId !=null)
                {
                    sql+= $" and a.UserId = {userId}";
                }
                var list = conn.Query<SysMenu>(sql).ToList();
                return GetMenuResponsess(list);
            }
        }

        public List<MenuResponse> GetMenuResponsess(List<SysMenu> sysMenus, string parentMenuId = "")
        {
            return sysMenus.Where(p => p.Type == Config.SysConstants.MenuType.Menu && p.ParentMenuId == parentMenuId && p.Deleted == false).Select(p => new MenuResponse
            {
                Icon = p.Icon,
                Type = p.Type,
                Level = p.Level,
                MenuId = p.MenuId,
                MenuName = p.MenuName,
                OrderIndex = p.OrderIndex,
                ParentMenuId = parentMenuId,
                Url = p.Url,
                ChildMenus = GetMenuResponsess(sysMenus,p.MenuId).Count==0?null: GetMenuResponsess(sysMenus,p.MenuId)

            }).ToList();
        }


    }
}

三、控制器

using BaWei.RBACExam.Config;
using BaWei.RBACExam.DapperRepository.Repository;
using BaWei.RBACExam.Model.Dto.RequestParamsDto;
using BaWei.RBACExam.Model.SysDomain;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BaWei.RBACExam.AdminWebApi.Controllers
{
    //授权
    [Authorize]
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MenuController : ControllerBase
    {
        private readonly MemuRepository _memuRepository;
        private readonly Repostitory _repostitory;
        private readonly AdminRepostory _adminRepostory;
        private readonly RoleRepostory _roleRepostory;
        private readonly JwtHelpers _jwtHelpers;

        public MenuController(MemuRepository memuRepository, Repostitory repository, AdminRepostory adminRepostory, RoleRepostory roleRepostory, JwtHelpers jwtHelpers)
        {
            _memuRepository = memuRepository;
            _repostitory = repository;
            _adminRepostory = adminRepostory;
            _roleRepostory = roleRepostory;
            _jwtHelpers = jwtHelpers;
        }
        /// <summary>
        /// 递归 导航
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMenus()
        {
           return Ok(_memuRepository.GetMenus());
        }

        /// <summary>
        /// 显示
        /// </summary>
        /// <param name="totalCount"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="sname"></param>
        /// <param name="youx"></param>
        /// <returns></returns>
       [HttpGet]
        public IActionResult GetAllShow(string sname, string youx, int pageindex = 1, int pagesize = 3)
        {
            try
            {
                var totalCount = 0;
                var list = _memuRepository.GetAllShow(out totalCount, sname, youx, pageindex, pagesize);
                return Ok(new { totalCount, list });
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 单删
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult DanShan(int id)
        {
            try
            {
                return Ok(_memuRepository.DanShan(id));
            }
            catch (Exception)
            {

                throw;
            }
        }


        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
       [HttpPost]
        public IActionResult PostAddUser(SysUser user)
        {
            try
            {
                return Ok(_memuRepository.PostAddUser(user));
            }
            catch (Exception)
            {

                 throw;
            }
        }


        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetRoleList()
        {
            try
            {
                return Ok(_memuRepository.GetRoleList());
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 添加 分配的角色 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostAllocation(SysUserRoleRelations sysUser)
        {
            try
            {
                return Ok(_repostitory.PostAllocation(sysUser));
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 根据用户ID获取所有加色ID
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetUserId(long userid)
        {
            try
            {
                return Ok(_repostitory.GetUserId(userid));
            }
            catch (Exception)
            {

                throw;
            }

        }

        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostUpdate(SysUser user)
        {
            try
            {
                return Ok(_memuRepository.PostUpdate(user));
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 显示管理
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMenuXiTOng(string sname, bool? state)
        {
            try
            {
                return Ok(_adminRepostory.GetMenuXiTOng(sname, state));
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 单删管理
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult DeletMen(string menuId)
        {
            try
            {
                return Ok(_adminRepostory.DeletMen(menuId));
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 角色权限的显示
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult AllShowShuJu()
        {
            try
            {
                return Ok(_memuRepository.AllShowShuJu());
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 角色权限的添加
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddJiaoRole(SysRole role)
        {
            try
            {
                return Ok(_memuRepository.AddJiaoRole(role));
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 角色权限的删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult RoleDelete(long roleId)
        {
            try
            {
                return Ok(_memuRepository.RoleDelete(roleId));
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 角色 权限 添加
        /// </summary>
        /// <param name="sysRole"></param>
        /// <returns></returns>
       [HttpPost]
        public IActionResult PostRole(SysRoleMenuRelations sysRole)
        {
            try
            {
                return Ok(_roleRepostory.PostRole(sysRole));
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 查看权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
       [HttpGet]
        public IActionResult EidBianJi(long roleId)
        {
            try
            {
                return Ok(_roleRepostory.EidBianJi(roleId));
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="snam"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        
        //任何请求都可以访问该方法
        [AllowAnonymous]
        [HttpPost]
        public IActionResult Register(string snam, string pwd)
        {
            try
            {
                var user = _roleRepostory.Register(snam, pwd);
                if(user.Success)
                {
                    var token = _jwtHelpers.GenerateToken(snam);
                    HttpContext.Response.Headers["token"]=token;
                    HttpContext.Response.Headers["Access-Control-Expose-Headers"] = "token";

                    return Ok(user);
                }
                else
                {
                    //失败的请求 状态码400
                    return Ok(user);
                }

            }
            catch (Exception)
            {

                throw;
            }
        }



        /// <summary>
        /// 根据登录人进行显示
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult JurisdictionShow(long? userId)
        {
            try
            {
                return Ok(_roleRepostory.JurisdictionShow(userId));
            }
            catch (Exception)
            {

                throw;
            }
        }

    }
}

 四、Vue显示页面

    1、使用方法

       创建 http.js存放

import axios from 'axios';//引用的axios


//实例化
const $http= axios.create({
    //自己的后台端口
    baseURL:'http://localhost:**08/api/',
    timeout:8000 //超时时间
})

//请求拦截
$http.interceptors.request.use(config=>{
    const token=localStorage.getItem('token');
    if(token){
        config.headers.Authorization='Bearer '+token;
    }
    return config;
})

//导出
export default $http;

      在main.js 进行 一下操作

import Vue from 'vue'
import App from './App.vue'
import router from './router'

import axios from './request/http'

import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.config.productionTip = false
Vue.prototype.$axios=axios

Vue.prototype.$http=axios

Vue.use(ElementUI);

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

    2、登录页面

<template>
  <div>
    <div class="back">
        <h2 class="ssg">登录</h2>
      <el-row :span="1">
        <el-col :span="15"
          ><el-input v-model="name" placeholder="请输入用户名" class="ssg1"></el-input
        ></el-col>
      </el-row>
      <el-row :span="1">
        <el-col :span="15">
          <el-input v-model="pwd" placeholder="请输入密码" class="ssg1" show-password></el-input
        ></el-col>
      </el-row>
      <el-row :span="1">
        <el-col :span="5" class="ssg2">
          <el-button @click="LoginLu()" class="sss">登录</el-button></el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "",
      pwd: "",
    };
  },
  methods: {
    LoginLu() {
      if (this.name.length == 0) {
        alert("用户名不能为空");
        return;
      }
      if (this.pwd.length == 0) {
        alert("密码不能为空");
        return;
      }
      this.$http
        .post(
          "Menu/Register?snam=" +
            this.name +
            "&pwd=" +
            this.pwd +
            ""
        )
        .then((res) => {
          if (res.data.Code==200) {
            alert("登录成功");
            //存储用户ID
            localStorage.setItem("userId",res.data.Data.UserId);
            //存储token
            localStorage.setItem("token",res.headers.token)
            this.$router.push("AllShow/");
          } else {
            alert("登录失败");
          }
        });
    },
  },
  created() {},
};
</script>

<style>
.back{
    width: 400px;
    height: 300px;
    border: 1px solid #ccc;
    margin-top: 180px;
    margin-left: 700px;
}
.ssg{
    margin-left: 150px;
}
.ssg1{
    margin-top: 10px;
    margin-left: 50px;
}
.ssg2{
    margin-top: 10px;
    margin-left: 110px;
}
.sss{
    width: 120px;
}
</style>

    3、布局页面

<template>
  <div>
    <el-container>
      <el-header>系统头</el-header>
      <el-container>
        <el-aside width="200px">
          <!-- <el-menu
      default-active="2"
      class="el-menu-vertical-demo"
      
      background-color="#545c64"
      text-color="#fff"
      active-text-color="#ffd04b"
      v-for="(item,index) in showData" :key="index">
      <el-submenu index="1">
        <template slot="title">
          <i class="el-icon-location"></i>
          <span>{{item.MenuName}}</span>
        </template>
          <el-menu-item 
          :index="items.MenuId"
          v-for="(items,indexs) in item.ChildMenus"
          :key="indexs"
          >{{items.MenuName}}</el-menu-item>
      </el-submenu> 
    </el-menu> -->

          <!-- 使用组件 -->
          <MenuTree :menuData="this.menuData"></MenuTree>
        </el-aside>
        <el-main>
          <router-view />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import MenuTree from "../components/MenuTree.vue";
export default {
  components: {
    MenuTree,
  },
  data() {
    return {
      menuData: [],
    };
  },
  methods: {
   //  getOpxians() {
   //    this.$http.get("http://localhost:1308/api/Menu/GetMenus").then((res) => {
   //      this.menuData = res.data;
   //    });
   //  },
//
   getOpxians() {
     let userIds = localStorage.getItem("userId");
     this.$http
       .get("Menu/JurisdictionShow?userId="+userIds)
       .then((res) => {
         this.menuData = res.data;
       });
   },
  },
  created() {
    this.getOpxians();
  },
};
</script>

<style>
.el-header,
.el-footer {
  background-color: #b3c0d1;
  color: #333;
  text-align: center;
  line-height: 60px;
}

.el-aside {
  background-color: #d3dce6;
  color: #333;
  text-align: center;
  line-height: 200px;
}

.el-main {
  background-color: #e9eef3;
  color: #333;
  text-align: center;
  line-height: 60px;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}
</style>

    4、导航菜单

<template>
  <div>
      <el-menu
      default-active="2"
      background-color="#545c64"
      text-color="#fff"
      active-text-color="#ffd04b"
      router
      >
      <template v-for="item in this.menuData">
        <el-submenu v-if="item.ChildMenus!=null" :index="item.MenuId.toString()" :key="item.MenuId">
      <template slot="title">
        <i v-bind:class="item.Icon"></i>
        <span>{{item.MenuName}}</span>
      </template>
      <MenuTree :menuData="item.ChildMenus"></MenuTree>
    </el-submenu> 
    <el-menu-item v-else :key="item.MenuId"
        :index="item.Url"
        >
        <i :class="item.Icon"></i>
        {{item.MenuName}}</el-menu-item>
    </template>
    </el-menu>
  </div>
</template>

<script>
export default {
 name:'MenuTree',
 data(){
     return{

     }
 },
 props:['menuData'],  //子组件接收父组件的数据
 components:{

 }
}
</script>

<style>

</style>

    5、用户管理页面

<template>
  <div>
    <el-row :span="1">
      <el-col :span="1"> 用户名 </el-col>
      <el-col :span="5">
        <el-input v-model="sname" placeholder="用户名"></el-input>
      </el-col>
      <el-col :span="1"> 邮箱 </el-col>
      <el-col :span="5">
        <el-input v-model="youx" placeholder="邮箱"></el-input>
      </el-col>
      <el-col :span="1.5">
        <el-button @click="getshow()">查询</el-button>
      </el-col>
      <el-col :span="2">
        <el-button @click="dialogFormVisible = true">添加</el-button>
      </el-col>
    </el-row>
    <el-table
      ref="multipleTable"
      :data="show"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="NickName" label="用户名"> </el-table-column>
      <el-table-column prop="PassWord" label="密码"> </el-table-column>
      <el-table-column prop="Email" label="邮箱"> </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="Eidser(scope.row)">编辑</el-button>
          <el-button @click="Delets(scope.row.UserId)">删除</el-button>
          <el-button @click="dakai(scope.row)">分配角色</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageindex"
      :page-sizes="[1, 2, 3, 4]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
    >
    </el-pagination>
    <!--添加用户-->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="用户ID">
          <el-input v-model="form.UserId"></el-input>
        </el-form-item>
        <el-form-item label="用户名称">
          <el-input v-model="form.NickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码">
          <el-input v-model="form.PassWord"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱">
          <el-input v-model="form.Email"></el-input>
        </el-form-item>
        <el-form-item label="用户性别">
          <el-radio-group v-model="form.Sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户添加时间">
          <el-date-picker
            v-model="form.CreatedTime"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="用户时间">
          <el-date-picker
            v-model="form.UpdatedTime"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="postAddUser()">确 定</el-button>
      </div>
    </el-dialog>
    <!--修改用户-->
    <el-dialog title="修改用户" :visible.sync="dialogFormVisible2">
      <el-form :model="form2">
        <el-form-item label="用户ID">
          <el-input v-model="form2.UserId"></el-input>
        </el-form-item>
        <el-form-item label="用户名称">
          <el-input v-model="form2.NickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码">
          <el-input v-model="form2.PassWord"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱">
          <el-input v-model="form2.Email"></el-input>
        </el-form-item>
        <el-form-item label="用户性别">
          <el-radio-group v-model="form2.Sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户添加时间">
          <el-date-picker
            v-model="form2.CreatedTime"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="用户时间">
          <el-date-picker
            v-model="form2.UpdatedTime"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="postEidUp()">保存</el-button>
      </div>
    </el-dialog>
    <!--分配角色-->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span>分配角色</span>
      <el-tree
        :data="roleTree"
        show-checkbox
        node-key="RoleId"
        ref="tree"
        :props="defaultProps"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="AddJurisdiction">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      show: [],
      sname: "",
      youx: "",
      pageindex: 1,
      pagesize: 3,
      totalCount: 0,
      //添加
      dialogFormVisible: false,
      //修改
      dialogFormVisible2: false,

      dialogVisible: false,
      form: {
        UserId: "",
        NickName: "",
        PassWord: "",
        Email: "",
        Sex: "",
        CreatedTime: "",
        UpdatedTime: "",
      },
      form2: {
        UserId: "",
        NickName: "",
        PassWord: "",
        Email: "",
        Sex: "",
        CreatedTime: "",
        UpdatedTime: "",
      },
      //角色的字段关联
      defaultProps: {
        children: "children",
        label: "RoleName",
        id: "RoleId",
      },
      roleTree: [],
      UserId: "",

      //角色ID
      roleId: "",
      roles: [],

      showId: [],

      gaiId: "",
    };
  },
  methods: {
    //显示
    getshow() {
      this.$http
        .get(
          "Menu/GetAllShow?sname=" +
            this.sname +
            "&youx=" +
            this.youx +
            "&pageindex=" +
            this.pageindex +
            "&pagesize=" +
            this.pagesize +
            ""
        )
        .then((res) => {
          this.show = res.data.list;
          this.totalCount = res.data.totalCount;
        });
    },
    //获取角色列表
    getRoleLists() {
      this.$http
        .get("Menu/GetRoleList")
        .then((res) => {
          this.roleTree = res.data.PageData;
        });
    },

    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    handleSizeChange(val) {
      //console.log(`每页 ${val} 条`);
      this.pagesize = val;
      this.getshow();
    },
    handleCurrentChange(val) {
      //console.log(`当前页: ${val}`);
      this.pageindex = val;
      this.getshow();
    },
    //查看详情
    Eidser(row) {
      this.dialogFormVisible2 = true;
      this.form2=row;
    },
    //修改用户数据
    postEidUp(){
      this.$http.post("Menu/PostUpdate",this.form2).then(res=>{
        if(res.data>0)
        {
          alert("修改成功");
          this.dialogFormVisible2 = false;
        }
        else{
          alert("修改失败");
        }
      })
    },

    //添加
    postAddUser() {
      this.$http
        .post("Menu/PostAddUser", this.form)
        .then((res) => {
          if (res.data > 0) {
            alert("添加成功");
            this.dialogFormVisible = false;
          } else {
            alert("添加失败");
          }
        });
    },

    //删除
    Delets(id) {
      if (confirm("是否确定删除")) {
        this.$http
          .get("/Menu/DanShan?id=" + id)
          .then((res) => {
            if (res.data > 0) {
              alert("删除成功");
              this.getshow();
            } else {
              alert("删除失败");
            }
          });
      }
    },
    //分配角色
    dakai(row) {
      this.dialogVisible = true;
      this.UserId = row.UserId;
      this.roles = [];
      //显示选中的权限
      this.$http
        .get("Menu/GetUserId?userid=" + this.UserId)
        .then((res) => {
          this.showId = res.data.PageData;
          this.showId.forEach((item) => {
            this.roles.push(item.RoleId);
          });
          this.$nextTick(() => {
            this.$refs.tree.setCheckedKeys(this.roles);
          });
        });
    },
    //保存角色
    AddJurisdiction() {
      this.dialogVisible = false;
      this.roles = [];
      //获取角色ID
      let nodes = this.$refs.tree.getCheckedNodes();
      nodes.filter((item) => {
        this.roles.push(item.RoleId);
      });
      console.log(this.roles);
      //获取
      this.$http
        .post("Menu/PostAllocation", {
          UserId: this.UserId,
          RoleIds: this.roles.toString(),
        })
        .then((res) => {
          if (res.data.Code > 0) {
            alert("添加成功");
          } else {
            alert("添加失败");
          }
        });
    },
    handleClose() {},
  },
  created() {
    this.getshow();
    this.getRoleLists();
  },
};
</script>

<style>
</style>

    6、菜单管理

<template>
  <div>
    <el-row :span="1">
  <el-col :span="1.5"> 菜单名称 </el-col>
  <el-col :span="4">
    <el-input v-model="sname" placeholder="请输入菜单名称"></el-input>
  </el-col>
  <el-col :span="1.5"> 菜单状态 </el-col>
  <el-col :span="4">
    <el-input v-model="state" placeholder="正常"></el-input>
  </el-col>
  <el-col :span="1.5">
    <el-button @click="xianshi()">查询</el-button>
  </el-col>
  <el-col :span="2">
    <el-button>重置</el-button>
  </el-col>
</el-row>
    <el-table
      :data="tableData1"
      style="width: 100%"
      row-key="MenuId"
      border
      :tree-props="{ children: 'ChildMenus' }"
    >
      <el-table-column prop="MenuName" label="系统管理" width="180">
      </el-table-column>
      <el-table-column prop="Icon" label="图标" width="180"> </el-table-column>
      <el-table-column prop="Type" label="菜单类型"> </el-table-column>
      <el-table-column prop="Url" label="路由地址"> </el-table-column>
      <el-table-column label="菜单状态"> </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button>新增</el-button>
          <el-button>编辑</el-button>
          <el-button @click="danDateAdmi(scope.row.MenuId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      sname:"",
      state:"",
      tableData1: [],
    };
  },
  methods: {
    xianshi() {
      this.$http
        .get("Menu/GetMenuXiTOng?sname="+this.sname+"&state="+this.state+"")
        .then((res) => {
          this.tableData1 = res.data;
        });
    },
    danDateAdmi(MenuId){
      if(confirm("是否确定删除?"))
      {
        this.$http.get("Menu/DeletMen?menuId="+MenuId).then(res=>{
          if(res.data>0)
          {
            alert("删除成功");
            this.xianshi();
          }
          else{
            alert("删除失败");
          }
        })
      }
    }
  },
  created() {
    this.xianshi();
  },
};
</script>

<style>
</style>

    7、角色管理

<template>
  <div>
    <el-row :span="1">
      <el-col :span="1.5"> 角色名称 </el-col>
      <el-col :span="5">
        <el-input placeholder="角色名称"></el-input>
      </el-col>
      <el-col :span="1.5">
        <el-button @click="getshow()">查询</el-button>
      </el-col>
      <el-col :span="2">
        <el-button @click="dialogFormVisible = true">添加</el-button>
      </el-col>
    </el-row>
    <el-table
      ref="multipleTable"
      :data="show"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="RoleName" label="角色名称"> </el-table-column>
      <el-table-column prop="RoleDesc" label="备注"> </el-table-column>
      <el-table-column label="权限列表"> </el-table-column>
      <el-table-column label="关联用户"> </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="eidser(scope.row)">编辑</el-button>
          <el-button @click="rolDelete(scope.row)">删除</el-button>
          <el-button @click="AllShowGuan(scope.row)">分配角色</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--添加-->
    <el-dialog title="添加角色" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="角色ID">
          <el-input v-model="form.RoleId"></el-input>
        </el-form-item>
        <el-form-item label="角色名称">
          <el-input v-model="form.RoleName"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.RoleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="postAddRole()">确 定</el-button>
      </div>
    </el-dialog>
    <!--修改-->
    <el-dialog title="修改角色" :visible.sync="dialogFormVisible2">
      <el-form :model="form">
        <el-form-item label="角色ID">
          <el-input v-model="form.RoleId"></el-input>
        </el-form-item>
        <el-form-item label="角色名称">
          <el-input v-model="form.RoleName"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.RoleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="postAddRole()">确 定</el-button>
      </div>
    </el-dialog>

    <!--分配角色-->
    <el-dialog title="分配角色" :visible.sync="dialogFormVisible3">
      <el-tree
        :data="reild"
        show-checkbox
        node-key="MenuId"
        ref="tree"
        default-expand-all
        :props="defaultProps"
      >
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="addJurisdi()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      show: [],
      form: {
        RoleId: "",
        RoleName: "",
        RoleDesc: "",
      },
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogFormVisible3: false,
      defaultProps: {
        children: "ChildMenus",
        label: "MenuName",
        id: "MenuId",
      },
      reild: [],
      chenckedKeys: [],
      checkedkyyesHalf: [],
      roleId: "",
    };
  },
  methods: {
    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //显示
    allShowRole() {
      this.$http
        .get("Menu/AllShowShuJu")
        .then((res) => {
          this.show = res.data;
        });
    },
    //添加
    postAddRole() {
      this.$http
        .post("Menu/AddJiaoRole", this.form)
        .then((res) => {
          if (res.data > 0) {
            alert("添加成功");
            this.dialogFormVisible = false;
            this.allShowRole();
          } else {
            alert("添加失败");
          }
        });
    },
    rolDelete(row) {
      if (confirm("是否确定删除?")) {
        this.$http
          .get("Menu/RoleDelete?roleId=" + row.RoleId)
          .then((res) => {
            if (res.data > 0) {
              alert("删除成功");
              this.allShowRole();
            } else {
              alert("删除失败");
            }
          });
      }
    },
    //查看详情
    eidser(row) {
      this.dialogFormVisible2 = true;
      this.form = row;
    },
    //管理显示
    AllShowGuan(row) {
      this.dialogFormVisible3 = true;
      this.roleId = row.RoleId;
      this.$http.get("Menu/GetMenus").then((res) => {
        this.reild = res.data;
      });

      this.$http
        .get("Menu/EidBianJi?roleId=" + row.RoleId)
        .then((res) => {
          this.$refs.tree.setCheckedKeys([]);
          res.data.filter((i) => {
            var node = this.$refs.tree.getNode(i.MenuId);
            if (node.isLeaf) {
              this.$refs.tree.setChecked(node, true);
            }
          });
        });
    },
    //给角色添加权限
    addJurisdi() {
      this.dialogFormVisible3 = false;
      this.chenckedKeys = this.$refs.tree.getCheckedKeys();
      this.checkedkyyesHalf = this.$refs.tree.getHalfCheckedKeys();
      //添加角色权限
      this.$http
        .post("Menu/PostRole", {
          RoleIds: this.roleId,
          MenuIds: this.chenckedKeys.concat(this.checkedkyyesHalf).toString(),
        })
        .then((res) => {
          if (res.data > 0) {
            alert("配置权限成功");
          } else {
            alert("配置权限失败");
          }
        });
    },
  },
  created() {
    this.allShowRole();
    this.AllShowGuan;
  },
};
</script>

<style>
</style>

     8、图解

 

 

 

 

 

 

 

 

 

     

      ......待续

 

  

 

posted @ 2021-11-17 13:33  魔术人生  阅读(310)  评论(0编辑  收藏  举报
复制代码