欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-22 09:52:20
数据结构 权限分配 1.在项目中新建文件夹helpers 2.在hr.helpers文件夹下添加enummoudle.cs 复制代码 代码如下: name...

数据结构

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

权限分配

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

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