佳木斯湛栽影视文化发展公司

主頁 > 知識(shí)庫 > ASP.NET.4.5.1+MVC5.0設(shè)置系統(tǒng)角色與權(quán)限(一)

ASP.NET.4.5.1+MVC5.0設(shè)置系統(tǒng)角色與權(quán)限(一)

熱門標(biāo)簽:阿里云 科大訊飛語音識(shí)別系統(tǒng) 硅谷的囚徒呼叫中心 百度競(jìng)價(jià)排名 地方門戶網(wǎng)站 網(wǎng)站排名優(yōu)化 集中運(yùn)營(yíng)管理辦法 服務(wù)器配置

數(shù)據(jù)結(jié)構(gòu)

權(quán)限分配

1.在項(xiàng)目中新建文件夾Helpers

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

復(fù)制代碼 代碼如下:

namespace HR.Helpers
{
    public enum EnumMoudle
    {
        /// summary>
        /// 模塊
        /// /summary>
        [EnumTitle("用戶管理")]
        SysUserManage_Role = 102,
        [EnumTitle("機(jī)構(gòu)管理")]
        Department = 201,
        [EnumTitle("人事資料")]
        Employees = 301,
        [EnumTitle("系統(tǒng)管理")]
        BaseInfo = 404,
    }
}

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

復(fù)制代碼 代碼如下:

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>
        /// 當(dāng)彈出DIV彈窗時(shí),需要刷新瀏覽器整個(gè)頁面
        /// /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關(guān)閉彈窗
        /// /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>
        /// 轉(zhuǎn)向到一個(gè)提示頁面,然后自動(dòng)返回指定的頁面
        /// /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>
        /// 在方法執(zhí)行前更新操作人
        /// /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執(zhí)行后
        /// /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);
            //在方法執(zhí)行前,附加上PageSize值
            filterContext.ActionParameters.Values.Where(v => v is Request).ToList().ForEach(v => ((Request)v).PageSize = this.PageSize);
        }
        /// summary>
        /// 產(chǎn)生一些視圖數(shù)據(jù)
        /// /summary>
        protected virtual void RenderViewData()
        {
        }
        /// summary>
        /// 當(dāng)前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>
        /// 發(fā)生異常寫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.在項(xiàng)目文件夾中新建ControllerBase.cs

復(fù)制代碼 代碼如下:

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.在項(xiàng)目中新建RoleControllerBase.cs

復(fù)制代碼 代碼如下:

namespace HR
{
    public class RoleControllerBase : ControllerBase
    {
        SystemUserRepository sysuserrepository = new SystemUserRepository();
        /// summary>
        /// 用戶權(quán)限
        /// /summary>
        public virtual ListEnumMoudle> PermissionList
        {
            get
            {
                var permissionList = new ListEnumMoudle>();
                return permissionList;
            }
        }
        public string BusinessPermissionString { get; set; }
        [NotMapped]
        public ListEnumMoudle> BusinessPermissionList
        {
            get
            {
                if (string.IsNullOrEmpty(BusinessPermissionString))
                    return new ListEnumMoudle>();
                else
                    return BusinessPermissionString.Split(",".ToCharArray()).Select(p => int.Parse(p)).CastEnumMoudle>().ToList();
            }
            set
            {
                BusinessPermissionString = string.Join(",", value.Select(p => (int)p));
            }
        }
        /// summary>
        /// Action方法執(zhí)行前沒有權(quán)限提示信息
        /// /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).CastPermissionAttribute>();
            permissionAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(PermissionAttribute), false).CastPermissionAttribute>().Union(permissionAttributes);
            var attributes = permissionAttributes as IListPermissionAttribute> ?? 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("您沒有權(quán)限!", "/default/ng");
                         else
                             filterContext.Result = Content("您沒有權(quán)限!");
                     }
                 }
            }
        }
    }
}

6.在每個(gè)Controller繼承RoleControllerBase類

public class EmployeesController : RoleControllerBase

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

復(fù)制代碼 代碼如下:

namespace HR.Helpers
{
    public class PermissionAttribute : FilterAttribute, IActionFilter
    {
        public ListEnumMoudle> 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方法加上驗(yàn)證

復(fù)制代碼 代碼如下:

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

9.在用戶管理Controller中添加權(quán)限分配,修改方法

復(fù)制代碼 代碼如下:

        #region 添加管理員
        /// summary>
        /// 添加頁
        /// /summary>
        /// param name="model">管理員實(shí)體類/param>
        /// returns>/returns>
        [Authorize]
        public ActionResult Add()
        {
            var moudleList = EnumHelper.GetItemValueListEnumMoudle>();
            this.ViewBag.MoudleList = new SelectList(mouldeList, "Key", "Value");
            return View();
        }
        /// summary>
        /// 添加事件
        /// /summary>
        /// param name="model">實(shí)體類/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
        //修改權(quán)限
        [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

復(fù)制代碼 代碼如下:

        [Authorize]
        public ActionResult Edit(int id)
        {
            var model = systemuserrepository.GetModel(id);
            if (model != null)
            {
                var moudleList = EnumHelper.GetItemValueListEnumBusinessPermission>();
                this.ViewBag.MoudleList = new SelectList(moudleList, "Key", "Value", string.Join(",", model.BusinessPermissionString.ToString()));
                return View(model);
            }
            else
                return View("404");
        }

以上就是本文的全部?jī)?nèi)容了,后續(xù)我們將持續(xù)更新,小伙伴們是否喜歡本系列文章呢?

您可能感興趣的文章:
  • .NET Web開發(fā)之.NET MVC框架介紹
  • asp.net mvc下拉框Html.DropDownList 和DropDownListFor的常用方法
  • 使用asp.net MVC4中的Bundle遇到的問題及解決辦法分享
  • asp.net MVC實(shí)現(xiàn)無組件上傳圖片實(shí)例介紹
  • Asp.net實(shí)現(xiàn)MVC處理文件的上傳下載功能實(shí)例教程
  • asp.net如何進(jìn)行mvc異步查詢

標(biāo)簽:西雙版納 威海 廣西 甘孜 梧州 隨州 烏蘭察布 開封

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《ASP.NET.4.5.1+MVC5.0設(shè)置系統(tǒng)角色與權(quán)限(一)》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    互助| 句容市| 博乐市| 垣曲县| 西青区| 自治县| 周至县| 太仓市| 个旧市| 金坛市| 云安县| 包头市| 新余市| 梓潼县| 玛多县| 正镶白旗| 德庆县| 马尔康县| 怀来县| 平潭县| 郎溪县| 南充市| 江北区| 修文县| 阳新县| 嘉祥县| 宜兴市| 大安市| 新绛县| 台南县| 安乡县| 北宁市| 保靖县| 泗阳县| 仁布县| 黄山市| 延长县| 海伦市| 镇平县| 麟游县| 永善县|