主攻ASP.NET.4.5.1 MVC5.0之重生:系统角色与权限(一)_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > 主攻ASP.NET.4.5.1 MVC5.0之重生:系统角色与权限(一)

主攻ASP.NET.4.5.1 MVC5.0之重生:系统角色与权限(一)

 2014/4/24 10:28:02  小念头  博客园  我要评论(0)
  • 摘要:数据结构权限分配1.在项目中新建文件夹Helpers2.在HR.Helpers文件夹下添加EnumMoudle.CsnamespaceHR.Helpers{publicenumEnumMoudle{///<summary>///模块///</summary>[EnumTitle("用户管理")]SysUserManage_Role=102,[EnumTitle("机构管理")]Department=201,[EnumTitle("人事资料")]Employees=301
  • 标签:

数据结构

权限分配

 

1.在项目中新建文件夹Helpers

2.在HR.Helpers文件夹下添加EnumMoudle.Cs 

namespace HR.Helpers
{
    public enum EnumMoudle
    {
        /// <summary>
        /// 模块
        /// </summary>
        [EnumTitle("用户管理")]
        SysUserManage_Role = 102,
[EnumTitle(
"机构管理")] Department = 201, [EnumTitle("人事资料")] Employees = 301, [EnumTitle("系统管理")] BaseInfo = 404, } }

3.在HR.Helpers文件夹下添加ControllerBase.Cs 

class="code_img_closed" src="/Upload/Images/2014042410/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('8f26066e-8985-4d7c-8793-318a7e29f51f',event)" src="/Upload/Images/2014042410/2B1B950FA3DF188F.gif" alt="" />
  1 namespace HR.Helpers
  2 {
  3     public class ControllerBase : Controller
  4     {
  5         /// <summary>
  6         /// 操作人,传IP....到后端记录
  7         /// </summary>
  8         public virtual Operater Operater
  9         {
 10             get
 11             {
 12                 return null;
 13             }
 14         }
 15 
 16         /// <summary>
 17         /// 分页大小
 18         /// </summary>
 19         public virtual int PageSize
 20         {
 21             get
 22             {
 23                 return 15;
 24             }
 25         }
 26 
 27         protected ContentResult JsonP(string callback, object data)
 28         {
 29             var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
 30             return this.Content(string.Format("{0}({1})", callback, json));
 31         }
 32 
 33         /// <summary>
 34         /// 当弹出DIV弹窗时,需要刷新浏览器整个页面
 35         /// </summary>
 36         /// <returns></returns>
 37         public ContentResult RefreshParent(string alert = null)
 38         {
 39             var script = string.Format("<script>{0}; parent.location.reload(1)</script>", string.IsNullOrEmpty(alert) ? string.Empty : "alert('" + alert + "')");
 40             return this.Content(script);
 41         }
 42 
 43         public new ContentResult RefreshParentTab(string alert = null)
 44         {
 45             var script = string.Format("<script>{0}; if (window.opener != null) {{ window.opener.location.reload(); window.opener = null;window.open('', '_self', '');  window.close()}} else {{parent.location.reload(1)}}</script>", string.IsNullOrEmpty(alert) ? string.Empty : "alert('" + alert + "')");
 46             return this.Content(script);
 47         }
 48 
 49         /// <summary>
 50         ///JS关闭弹窗
 51         /// </summary>
 52         /// <returns></returns>
 53         public ContentResult CloseThickbox()
 54         {
 55             return this.Content("<script>top.tb_remove()</script>");
 56         }
 57 
 58         /// <summary>
 59         ///  警告并且历史返回
 60         /// </summary>
 61         /// <param name="notice"></param>
 62         /// <returns></returns>
 63         public ContentResult Back(string notice)
 64         {
 65             var content = new StringBuilder("<script>");
 66             if (!string.IsNullOrEmpty(notice))
 67                 content.AppendFormat("alert('{0}');", notice);
 68             content.Append("history.go(-1)</script>");
 69             return this.Content(content.ToString());
 70         }
 71 
 72 
 73         public ContentResult PageReturn(string msg, string url = null)
 74         {
 75             var content = new StringBuilder("<script type='text/javascript'>");
 76             if (!string.IsNullOrEmpty(msg))
 77                 content.AppendFormat("alert('{0}');", msg);
 78             if (string.IsNullOrWhiteSpace(url))
 79                 url = Request.Url.ToString();
 80             content.Append("window.location.href='" + url + "'</script>");
 81             return this.Content(content.ToString());
 82         }
 83 
 84         /// <summary>
 85         /// 转向到一个提示页面,然后自动返回指定的页面
 86         /// </summary>
 87         /// <param name="notice"></param>
 88         /// <param name="redirect"></param>
 89         /// <returns></returns>
 90         public ContentResult Stop(string notice, string redirect, bool isAlert = false)
 91         {
 92             var content = "<meta http-equiv='refresh' content='1;url=" + redirect + "' /><body style='margin-top:0px;color:red;font-size:24px;'>" + notice + "</body>";
 93 
 94             if (isAlert)
 95                 content = string.Format("<script>alert('{0}'); window.location.href='{1}'</script>", notice, redirect);
 96 
 97             return this.Content(content);
 98         }
 99 
100         /// <summary>
101         /// 在方法执行前更新操作人
102         /// </summary>
103         /// <param name="filterContext"></param>
104         public virtual void UpdateOperater(ActionExecutingContext filterContext)
105         {
106             if (this.Operater == null)
107                 return;
108 
109             WCFContext.Current.Operater = this.Operater;
110         }
111 
112         public virtual void ClearOperater()
113         {
114             //TODO
115         }
116 
117         /// <summary>
118         /// AOP拦截,在Action执行后
119         /// </summary>
120         /// <param name="filterContext">filter context</param>
121         protected override void OnActionExecuted(ActionExecutedContext filterContext)
122         {
123             base.OnActionExecuted(filterContext);
124             if (!filterContext.RequestContext.HttpContext.Request.IsAjaxRequest() && !filterContext.IsChildAction)
125                 RenderViewData();
126 
127             this.ClearOperater();
128         }
129 
130         protected override void OnActionExecuting(ActionExecutingContext filterContext)
131         {
132             this.UpdateOperater(filterContext);
133             base.OnActionExecuting(filterContext);
134 
135             //在方法执行前,附加上PageSize值
136             filterContext.ActionParameters.Values.Where(v => v is Request).ToList().ForEach(v => ((Request)v).PageSize = this.PageSize);
137         }
138 
139         /// <summary>
140         /// 产生一些视图数据
141         /// </summary>
142         protected virtual void RenderViewData()
143         {
144         }
145 
146         /// <summary>
147         /// 当前Http上下文信息,用于写Log或其他作用
148         /// </summary>
149         public WebExceptionContext WebExceptionContext
150         {
151             get
152             {
153                 var exceptionContext = new WebExceptionContext
154                 {
155                     IP = Fetch.UserIp,
156                     CurrentUrl = Fetch.CurrentUrl,
157                     RefUrl = (Request == null || Request.UrlReferrer == null) ? string.Empty : Request.UrlReferrer.AbsoluteUri,
158                     IsAjaxRequest = (Request == null) ? false : Request.IsAjaxRequest(),
159                     FormData = (Request == null) ? null : Request.Form,
160                     QueryData = (Request == null) ? null : Request.QueryString,
161                     RouteData = (Request == null || Request.RequestContext == null || Request.RequestContext.RouteData == null) ? null : Request.RequestContext.RouteData.Values
162                 };
163 
164                 return exceptionContext;
165             }
166         }
167 
168         /// <summary>
169         /// 发生异常写Log
170         /// </summary>
171         /// <param name="filterContext"></param>
172         protected override void OnException(ExceptionContext filterContext)
173         {
174             base.OnException(filterContext);
175             var e = filterContext.Exception;
176 
177             LogException(e, this.WebExceptionContext);
178         }
179 
180         protected virtual void LogException(Exception exception, WebExceptionContext exceptionContext = null)
181         {
182             //do nothing!
183         }
184     }
185 
186     public class WebExceptionContext
187     {
188         public string IP { get; set; }
189         public string CurrentUrl { get; set; }
190         public string RefUrl { get; set; }
191         public bool IsAjaxRequest { get; set; }
192         public NameValueCollection FormData { get; set; }
193         public NameValueCollection QueryData { get; set; }
194         public RouteValueDictionary RouteData { get; set; }
195     }
196 }
View Code

4.在项目文件夹中新建ControllerBase.cs

namespace HR
{
    public abstract class ControllerBase:HR.Helpers.ControllerBase
    {
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
        }
    }
}

5.在项目中新建RoleControllerBase.cs

namespace HR
{
    public class RoleControllerBase : ControllerBase
    {
        SystemUserRepository sysuserrepository = new SystemUserRepository();
        /// <summary>
        /// 用户权限
        /// </summary>
        public virtual List<EnumMoudle> PermissionList
        {
            get
            {
                var permissionList = new List<EnumMoudle>();
                return permissionList;
            }
        }
        public string BusinessPermissionString { get; set; }
        [NotMapped]
        public List<EnumMoudle> BusinessPermissionList 
        {
            get
            {
                if (string.IsNullOrEmpty(BusinessPermissionString))
                    return new List<EnumMoudle>();
                else
                    return BusinessPermissionString.Split(",".ToCharArray()).Select(p => int.Parse(p)).Cast<EnumMoudle>().ToList();
            }
            set
            {
                BusinessPermissionString = string.Join(",", value.Select(p => (int)p));
            }
        }
        /// <summary>
        /// Action方法执行前没有权限提示信息
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var noAuthorizeAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeIgnoreAttribute), false);
            if (noAuthorizeAttributes.Length > 0)
                return;

            base.OnActionExecuting(filterContext);

   
            bool hasPermission = true;
            var permissionAttributes = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(PermissionAttribute), false).Cast<PermissionAttribute>();
            permissionAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(PermissionAttribute), false).Cast<PermissionAttribute>().Union(permissionAttributes);
            var attributes = permissionAttributes as IList<PermissionAttribute> ?? permissionAttributes.ToList();
            if (permissionAttributes != null && attributes.Count() > 0)
            {
                 string cookie = CookieHelper.GetValue("SystemUserID");
                 if (string.IsNullOrEmpty(cookie))
                 {
                     filterContext.Result = Content("您没有登录!");
                 }
                 else
                 {
                     int mid = int.Parse(CookieHelper.GetValue("SystemUserID"));
                     var model = sysuserrepository.GetModel(mid);
                     BusinessPermissionString = model.BusinessPermissionString;
                     hasPermission = true;
                     foreach (var attr in attributes)
                     {
                         foreach (var permission in attr.Permissions)
                         {
                             if (!BusinessPermissionList.Contains(permission))
                             {
                                 hasPermission = false;
                                 break;
                             }
                         }
                     }

                     if (!hasPermission)
                     {
                         if (Request.UrlReferrer != null)
                             filterContext.Result = this.Stop("您没有权限!", "/default/ng");
                         else
                             filterContext.Result = Content("您没有权限!");
                     }
                 }
            }
        }
    }
}

 

6.在每个Controller继承RoleControllerBase类

public class EmployeesController : RoleControllerBase

7.在HR.Helpers文件夹下添加PermissionAttribute.Cs ,并继承 FilterAttribute, IActionFilter

namespace HR.Helpers
{
    public class PermissionAttribute : FilterAttribute, IActionFilter
    {
        public List<EnumMoudle> Permissions { get; set; }

        public PermissionAttribute(params EnumMoudle[] parameters)
        {
            Permissions = parameters.ToList();
        }

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            //throw new NotImplementedException();
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //throw new NotImplementedException();
        }
    }
}

 

8.然后在Controller或者Action方法加上验证

 [Permission(EnumMoudle.Employees),Authorize, ValidateInput(false)]
 [Permission(EnumMoudle.SysUserManage_Role)]

9.在用户管理Controller中添加权限分配,修改方法

        #region 添加管理员
        /// <summary>
        /// 添加页
        /// </summary>
        /// <param name="model">管理员实体类</param>
        /// <returns></returns>
        [Authorize]
        public ActionResult Add()
        {
            var moudleList = EnumHelper.GetItemValueList<EnumMoudle>();
            this.ViewBag.MoudleList = new SelectList(mouldeList, "Key", "Value");

            return View();
        }
    

        /// <summary>
        /// 添加事件
        /// </summary>
        /// <param name="model">实体类</param>
        /// <param name="fc"></param>
        /// <returns></returns>
        [Authorize, HttpPost, ValidateInput(false)]
        public ActionResult Add(SystemUser model, FormCollection fc)
        {
            model.BusinessPermissionString = fc["MoudelList"];
            model.State = 1;
            model.CreateTime = DateTime.Now;
            systemuserrepository.SaveOrEditModel(model);
            return RedirectToAction("UserList");
        }
        #endregion

        //修改权限
        [Authorize, AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
        public ActionResult Edit(int id, FormCollection fc)
        {
            var model = systemuserrepository.GetModel(id);

            if (model != null)
            {
                string password = model.PassWord;
                if (Request.Form["PassWord"] != "")
                {
                    model.BusinessPermissionString = fc["MoudleList"];
                    UpdateModel(model);
                    systemuserrepository.SaveOrEditModel(model);
                }
                else
                {
                    model.BusinessPermissionString = fc["MoudleList"];
                    UpdateModel(model);
                    model.PassWord = password;
                    systemuserrepository.SaveOrEditModel(model);
                }
                return RedirectToAction("userlist");
            }
            else
                return View("404");
        }
        #endregion
        [Authorize]
        public ActionResult Edit(int id)
        {
            var model = systemuserrepository.GetModel(id);
            if (model != null)
            {
                var moudleList = EnumHelper.GetItemValueList<EnumBusinessPermission>();
                this.ViewBag.MoudleList = new SelectList(moudleList, "Key", "Value", string.Join(",", model.BusinessPermissionString.ToString()));

                return View(model);
            }
            else
                return View("404");
        }

 关于EnumHelper枚举帮助类代码

点击获取页面

 

声明:本博客高度重视知识产权保护,发现本博客发布的信息包含有侵犯其著作权的链接内容时,请联系我,我将第一时间做相应处理,联系邮箱ffgign@qq.com

 


作者:Mark Fan (小念头)    
来源:http://cube.cnblogs.com
说明:未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。如有疑问,可以通过 ffgign@qq.com 联系作者,本文章采用 知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议进行许可

 

 

Moudle
上一篇: vs .net WebForm 模板添加注释 下一篇: 没有下一篇了!
  • 相关文章
发表评论
用户名: 匿名