1-背景介绍
需要做一个简单权限系统,基于 角色,用户,菜单 的模式
基于IActionFilter全局拦截,在内部跳转或者浏览器跳转的时候,拦截是成功的,当通过AJAX 请求的时候,页面就不会跳转
2-登录后初始化该用户权限到redis 缓存
因为菜单没有设置失效机制,所以登录就刷新菜单缓存数据
3- 基于 IActionFilter 全局过滤
在OnActionExecuting 方法 用判断 改动作是否有权限,没有的话就跳转一个 拒绝访问的友好页面。
首先,我们需要判断是否是AJAX 请求,如果是的话,返回你的 正常的处理AJAX请求的返回JSON串 就可以了,前端就可以直接拿到然后做出正确的动作
如果不是则直接跳转无权限 访问 的页面
4- 代码及效果展示
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public void OnActionExecuting(ActionExecutingContext context) 2 { 3 var hasPermission = true; 4 //权限拦截 5 if (context.HttpContext.User.Identity.IsAuthenticated) 6 { 7 var identity = context.HttpContext.User as ClaimsPrincipal; 8 var accountId = identity.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value; 9 var accountName = identity.Claims.First(x => x.Type == ClaimTypes.Name).Value; 10 if (accountName != "admin") 11 { 12 var menuDatalist = _menuMudoleStore.GetSysmodules(Convert.ToInt32(accountId), accountName, openRedis: true); 13 var currentUrl = context.HttpContext.Request.Path.ToString().ToLower(); 14 if (currentUrl != "/Account/AccessDenied".ToLower()) 15 { 16 if (menuDatalist == null && menuDatalist.Count <= 0) 17 { 18 hasPermission = false; 19 } 20 else 21 { 22 var mtypeid = (int)SysModuleType.module; 23 var pageList = menuDatalist.Where(x => x.moduletypeid != mtypeid).ToList(); 24 if (!pageList.Any(x => x.url.ToLower() == currentUrl)) 25 { 26 hasPermission = false; 27 } 28 } 29 } 30 } 31 } 32 if (!hasPermission) 33 { 34 if (context.HttpContext.Request.IsAjax()) 35 { 36 context.Result = new JsonResult(new ReturnResult<string> 37 { 38 success = false, 39 status = 302, 40 message = "您无权限访问", 41 data= "/Account/AccessDenied" 42 }); 43 } 44 else 45 context.HttpContext.Response.Redirect("/Account/AccessDenied"); 46 } 47 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //初始化树 2 function initTree(roleid) { 3 $.ajax({ 4 url: '/Role/GetMenuTree', 5 type: 'get', 6 data: { 7 roleid: roleid 8 }, 9 success: function (result) { 10 console.log(result) 11 if (result.success) { 12 zTreeObj = $.fn.zTree.init($("#permissiontree"), setting, result.data); 13 // 14 toastr.info('数据加载成功', '提示'); 15 } else { 16 toastr.error(result.message, '警告'); 17 //权限拦截 18 if (result.status == 302) { 19 $('#authperssionsformmodal').modal('hide'); 20 //setTimeout(function () { 21 // window.location.href = result.data; 22 //}, 500); 23 } 24 } 25 $('#dvloading').modal('hide'); 26 }, 27 beforeSend: function () { 28 // Handle the beforeSend event 29 $("#dvloading").modal({ backdrop: 'static', keyboard: false }); 30 }, 31 complete: function (xhr) { 32 // Handle the complete event 33 $('#dvloading').modal('hide'); 34 35 }, 36 error: function (e) { 37 $('#dvloading').modal('hide'); 38 toastr.error('系统错误,请重试', '警告'); 39 window.clearInterval(timer); 40 } 41 }); 42 }