源码网,源码论坛,源码之家,商业源码,游戏源码下载,discuz插件,棋牌源码下载,精品源码论坛

 找回密码
 立即注册
楼主: ttx9n

[ASP.NET] ASP.NET.4.5.1+MVC5.0设置系统角色与权限(一)

[复制链接]

7万

主题

861

回帖

32万

积分

论坛元老

Rank: 8Rank: 8

积分
329525
发表于 2018-12-25 13:17:42 | 显示全部楼层 |阅读模式
这篇文章主要介绍了ASP.NET.4.5.1+MVC5.0设置系统角色与权限的部分内容,后续我们将继续讨论这个话题,希望小伙伴们喜欢。

数据结构

权限分配

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

复制代码 代码如下:
namespace HR.Helpers
{
    public class ControllerBase : Controller
    {
        /// <summary>
        /// 操作人,传IP....到后端记录
        /// </summary>
        public virtual Operater Operater
        {
            get
            {
                return null;
            }
        }
        /// <summary>
        /// 分页大小
        /// </summary>
        public virtual int PageSize
        {
            get
            {
                return 15;
            }
        }
        protected ContentResult JsonP(string callback, object data)
        {
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            return this.Content(string.Format("{0}({1})", callback, json));
        }
        /// <summary>
        /// 当弹出DIV弹窗时,需要刷新浏览器整个页面
        /// </summary>
        /// <returns></returns>
        public ContentResult RefreshParent(string alert = null)
        {
            var script = string.Format("<script>{0}; parent.location.reload(1)</script>", string.IsNullOrEmpty(alert) ? string.Empty : "alert('" + alert + "')");
            return this.Content(script);
        }
        public new ContentResult RefreshParentTab(string alert = null)
        {
            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 + "')");
            return this.Content(script);
        }
        /// <summary>
        /// 用JS关闭弹窗
        /// </summary>
        /// <returns></returns>
        public ContentResult CloseThickbox()
        {
            return this.Content("<script>top.tb_remove()</script>");
        }
        /// <summary>
        ///  警告并且历史返回
        /// </summary>
        /// <param name="notice"></param>
        /// <returns></returns>
        public ContentResult Back(string notice)
        {
            var content = new StringBuilder("<script>");
            if (!string.IsNullOrEmpty(notice))
                content.AppendFormat("alert('{0}');", notice);
            content.Append("history.go(-1)</script>");
            return this.Content(content.ToString());
        }
        public ContentResult PageReturn(string msg, string url = null)
        {
            var content = new StringBuilder("<script type='text/javascript'>");
            if (!string.IsNullOrEmpty(msg))
                content.AppendFormat("alert('{0}');", msg);
            if (string.IsNullOrWhiteSpace(url))
                url = Request.Url.ToString();
            content.Append("window.location.href='" + url + "'</script>");
            return this.Content(content.ToString());
        }
        /// <summary>
        /// 转向到一个提示页面,然后自动返回指定的页面
        /// </summary>
        /// <param name="notice"></param>
        /// <param name="redirect"></param>
        /// <returns></returns>
        public ContentResult Stop(string notice, string redirect, bool isAlert = false)
        {
            var content = "<meta http-equiv='refresh' content='1;url=" + redirect + "' /><body style='margin-top:0px;color:red;font-size:24px;'>" + notice + "</body>";
            if (isAlert)
                content = string.Format("<script>alert('{0}'); window.location.href='{1}'</script>", notice, redirect);
            return this.Content(content);
        }
        /// <summary>
        /// 在方法执行前更新操作人
        /// </summary>
        /// <param name="filterContext"></param>
        public virtual void UpdateOperater(ActionExecutingContext filterContext)
        {
            if (this.Operater == null)
                return;
            WCFContext.Current.Operater = this.Operater;
        }
        public virtual void ClearOperater()
        {
            //TODO
        }
        /// <summary>
        /// AOP拦截,在Action执行后
        /// </summary>
        /// <param name="filterContext">filter context</param>
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            if (!filterContext.RequestContext.HttpContext.Request.IsAjaxRequest() && !filterContext.IsChildAction)
                RenderViewData();
            this.ClearOperater();
        }
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            this.UpdateOperater(filterContext);
            base.OnActionExecuting(filterContext);
            //在方法执行前,附加上PageSize值
            filterContext.ActionParameters.Values.Where(v => v is Request).ToList().ForEach(v => ((Request)v).PageSize = this.PageSize);
        }
        /// <summary>
        /// 产生一些视图数据
        /// </summary>
        protected virtual void RenderViewData()
        {
        }
        /// <summary>
        /// 当前Http上下文信息,用于写Log或其他作用
        /// </summary>
        public WebExceptionContext WebExceptionContext
        {
            get
            {
                var exceptionContext = new WebExceptionContext
                {
                    IP = Fetch.UserIp,
                    CurrentUrl = Fetch.CurrentUrl,
                    RefUrl = (Request == null || Request.UrlReferrer == null) ? string.Empty : Request.UrlReferrer.AbsoluteUri,
                    IsAjaxRequest = (Request == null) ? false : Request.IsAjaxRequest(),
                    FormData = (Request == null) ? null : Request.Form,
                    QueryData = (Request == null) ? null : Request.QueryString,
                    RouteData = (Request == null || Request.RequestContext == null || Request.RequestContext.RouteData == null) ? null : Request.RequestContext.RouteData.Values
                };
                return exceptionContext;
            }
        }
        /// <summary>
        /// 发生异常写Log
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);
            var e = filterContext.Exception;
            LogException(e, this.WebExceptionContext);
        }
        protected virtual void LogException(Exception exception, WebExceptionContext exceptionContext = null)
        {
            //do nothing!
        }
    }
    public class WebExceptionContext
    {
        public string IP { get; set; }
        public string CurrentUrl { get; set; }
        public string RefUrl { get; set; }
        public bool IsAjaxRequest { get; set; }
        public NameValueCollection FormData { get; set; }
        public NameValueCollection QueryData { get; set; }
        public RouteValueDictionary RouteData { get; set; }
    }
}

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");
        }

以上就是本文的全部内容了,后续我们将持续更新,小伙伴们是否喜欢本系列文章呢?

回复

使用道具 举报

16

主题

2万

回帖

174

积分

注册会员

Rank: 2

积分
174
发表于 2022-8-23 17:19:03 | 显示全部楼层
看看看看
回复 支持 反对

使用道具 举报

4

主题

1万

回帖

60

积分

注册会员

Rank: 2

积分
60
发表于 2022-9-18 08:51:31 | 显示全部楼层
天天源码社区www.tiantianym.com
回复 支持 反对

使用道具 举报

0

主题

1万

回帖

0

积分

中级会员

Rank: 3Rank: 3

积分
0
发表于 2022-10-2 02:15:16 | 显示全部楼层
儿飞飞微风DVD谁vdsvd
回复 支持 反对

使用道具 举报

3

主题

2万

回帖

172

积分

注册会员

Rank: 2

积分
172
发表于 2022-12-21 07:32:25 | 显示全部楼层
那三门,你们谁寂寞才快乐撒
回复 支持 反对

使用道具 举报

0

主题

2万

回帖

0

积分

中级会员

Rank: 3Rank: 3

积分
0
发表于 2023-10-9 01:28:12 | 显示全部楼层
iiguuubhuiuihu
回复 支持 反对

使用道具 举报

0

主题

1万

回帖

0

积分

中级会员

Rank: 3Rank: 3

积分
0
发表于 2024-3-30 13:28:19 | 显示全部楼层
哈哈哈哈哈哈哈
回复 支持 反对

使用道具 举报

0

主题

1万

回帖

0

积分

中级会员

Rank: 3Rank: 3

积分
0
发表于 2024-6-26 15:21:31 | 显示全部楼层
借款金额看了就立刻
回复 支持 反对

使用道具 举报

3

主题

2万

回帖

301

积分

中级会员

Rank: 3Rank: 3

积分
301
发表于 2024-8-21 14:09:09 | 显示全部楼层
还可以不错
回复 支持 反对

使用道具 举报

26

主题

9071

回帖

140

积分

注册会员

Rank: 2

积分
140
发表于 2024-9-5 14:07:04 | 显示全部楼层
感谢楼主分享
回复 支持 反对

使用道具 举报

高级模式
B Color Image Link Quote Code Smilies

本版积分规则

手机版|小黑屋|网站地图|源码论坛 ( 海外版 )

GMT+8, 2024-11-29 19:57 , Processed in 0.086477 second(s), 22 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表