xi_de 2016-01-29 11:09 采纳率: 13%
浏览 1583

mvc4 用户和角色的权限 控制

我在项目中 现在要加 角色 和 用户的 访问权限 在网上也看到很多例子

我是这样做的
我在我的 父类里 先把 角色 和 用户的 访问页面 都真理好 contronl里继承这个类 然后判断这个用户和角色是否可以访问这个页面 如果不行想让它直接跳转到 error 页面来提示,可以 怎么都不能跳转

  public void MParent() {

            var routeDate = HttpContext.Request.RequestContext.RouteData;

            var area = routeDate.DataTokens["area"].ToString();
            var controller = routeDate.Values["controller"].ToString();
            var action = routeDate.Values["action"].ToString();

            //将角色模块权限加入缓存中
            List<RoleModuleRights> RoleModuleList = (List<RoleModuleRights>)CacheHelper.Get(Constants.RoleModuleRights_KEY, () =>
            {
                CacheHelper.Insert(Constants.RoleModuleRights_KEY, new SystemService().GetRoleModuleInfo().ConvertToEntityCollectionFunc<RoleModuleRights>());
            });
            //用户模块权限加入缓存中
            List<UserModuleRights> UserModuleList = (List<UserModuleRights>)CacheHelper.Get(Constants.UserModuleRights_KEY, () =>
            {

                CacheHelper.Insert(Constants.UserModuleRights_KEY, new SystemService().GetUserModuleInfo().ConvertToEntityCollectionFunc<UserModuleRights>());
            });
            string url = "/" + area + "/" + controller + "/" + action;
            bool RoleRights = RoleModuleList.Where(m => m.Url == url).First().RoleIDs.Contains(UserInfo.RoleID.ToString());
            bool UserRights = UserModuleList.Where(m => m.Url == url).First().UserIDs.Contains(UserInfo.UserID.ToString());
            if (!RoleRights && !UserRights)
            {
                ErrorView view = new ErrorView();
                view.Message = "你没有该页面的操作访问权限!";


                Response.Redirect(Server.MapPath(@"~/Views/Shared/Error.cshtml"));
                //HttpContext.Response.Redirect("/WebPages/Error.htm");
                return;
            }
            string code = Request.QueryString["MCode"] == null ? "" : Request.QueryString["MCode"].ToString();
            if (string.IsNullOrEmpty(code))
            {
                return;
            }
            AuthorizeKey Authorize =  new SystemService().GetButtonRights(UserInfo.UserID, code).ConvertToEntityFunc<AuthorizeKey>();
            ViewBag.AuthorizeKey = Authorize;
        }
  • 写回答

1条回答 默认 最新

  • threenewbee 2016-01-29 13:36
    关注

    角色 和 用户的 访问权限不要写在控制器里,不然每个都要写,应该写验证过滤器,用attribute去申明

    参考:http://blog.csdn.net/zht666/article/details/8525177

    评论

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择