1.利用反射获取当前程序集下的所有控制器和方法,拼接后写入到数据库。
public void GetRightInfo() { var ControllerIDMax = db.rights_info.Select(p => p.RightsID).Max() + 1; var controllerTypes = Assembly.GetExecutingAssembly().GetTypes().Where(p => typeof(IController).IsAssignableFrom(p)); foreach (var item in controllerTypes) { var actionMethods = item.GetMethods().Where(q => q.ReturnType.Name == "ActionResult"); foreach (var action in actionMethods) { var rightsName = item.Name.Replace("Controller", "").ToLower() + "/" + action.Name.ToLower(); var ControllerInfo = new rights_info() { RightsID = ControllerIDMax, RightsName =rightsName }; if (db.rights_info.Where(p => p.RightsName == rightsName).Count() == 0) { db.rights_info.AddObject(ControllerInfo); ControllerIDMax++; } } } db.SaveChanges(); }
2.重写ActionFilterAttribute的OnActionExecuting方法实现自定义action权限访问。
public override void OnActionExecuting(ActionExecutingContext filterContext) { //url of visit var controllerName = filterContext.RouteData.Values["controller"].ToString().ToLower(); var actionName = filterContext.RouteData.Values["action"].ToString().ToLower(); var url = controllerName + "/" + actionName; //get rights of user var userInfo = HttpContext.Current.Session["UserId"] == null ? "" : HttpContext.Current.Session["UserId"].ToString(); var right = db.cus_cusmanagersinfo.Where(p => p.cus_Id == userInfo).Select(p => p.cus_Rights).First().Split(','); //check long t = db.rights_info.Where(p => p.RightsName == url).Select(p => p.RightsID).First(); var check = right.Contains(t.ToString()); if (!check) { //Redirection filterContext.Result = new RedirectResult("/home/index"); } }