一个基于Asp.Net MVC的权限方案 |
本文标签:Asp.Net,MVC 1.数据结构 ![]() Mad_Popedom为权限表,Control记录控制器名,Action记录动作名 。 Mad_Role为角色表 。 2.权限控制的实现 复制代码 代码如下: using System.Collections.Generic; using System.Web.Mvc; using Madnet.Model.MadAdmin; using Madnet.BLL.MadAdmin; namespace Madnet.Controllers.MadAdmin { public class SupportFilterAttribute : ActionFilterAttribute { private bool _IsLogin = true; /// <summary> /// 是否需要登录 /// </summary> public bool IsLogin { set { _IsLogin = value; } get { if (System.Configuration.ConfigurationManager.AppSettings["IsLogin"] != null) { bool.TryParse(System.Configuration.ConfigurationManager.AppSettings["IsLogin"].ToString(), out _IsLogin); } return _IsLogin; } } public override void OnActionExecuting(ActionExecutingContext filterContext) { string controllerName = (string)filterContext.RouteData.Values["controller"]; string actionName = (string)filterContext.RouteData.Values["action"]; if (IsLogin && filterContext.HttpContext.Session["Login_User"] == null) { filterContext.HttpContext.Response.Redirect(new UrlHelper(filterContext.RequestContext).Action("Login", "Default")); filterContext.Result = new EmptyResult(); } else if (IsLogin && filterContext.HttpContext.Session["Login_User"] != null) { Mad_User user = filterContext.HttpContext.Session["Login_User"] as Mad_User; if (!user.is_super) { if (!GetPopedom(user).Exists(p => p.Controller_Name == controllerName.ToLower() && p.Action_Name == actionName.ToLower())) { filterContext.HttpContext.Response.Write("没有权限"); filterContext.Result = new EmptyResult(); } } } } /// <summary> /// 获取当前用户所有有权限执行的动作 /// </summary> /// <returns></returns> public List<Atmodel> GetPopedom(Mad_User user) { List<Atmodel> ats = new List<Atmodel>(); List<Mad_Popedom> pops = Mad_PopedomBLL.GetPopedombyUser(user.user_id); foreach (Mad_Popedom pop in pops) { ats.Add(new AtModel() { Controller_Name = pop.Control, Action_Name = pop.Action }); } return ats; } } } 解释一下,上面的代码就是在执行前,先获取登录用户可以运行的Controller-Action,然后和当前需要执行的Controller-Action比较,如存在,即通过,否则为没有权限执行 。 3.为动作添加权限 4.为角色额添加权限 5.结束 |