91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

ASP.NET.4.5.1+MVC5.0設置系統角色與權限的方法教程

發布時間:2021-09-29 09:05:55 來源:億速云 閱讀:110 作者:iii 欄目:開發技術

這篇文章主要介紹“ASP.NET.4.5.1+MVC5.0設置系統角色與權限的方法教程”,在日常操作中,相信很多人在ASP.NET.4.5.1+MVC5.0設置系統角色與權限的方法教程問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”ASP.NET.4.5.1+MVC5.0設置系統角色與權限的方法教程”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

數據結構

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

到此,關于“ASP.NET.4.5.1+MVC5.0設置系統角色與權限的方法教程”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

常宁市| 阿合奇县| 积石山| 建德市| 灵宝市| 大姚县| 福建省| 大城县| 吉木萨尔县| 白山市| 美姑县| 临颍县| 板桥市| 兴国县| 文安县| 济源市| 五峰| 治县。| 伊金霍洛旗| 华阴市| 华安县| 新邵县| 措美县| 石家庄市| 晋江市| 永城市| 庐江县| 吉水县| 宜都市| 高唐县| 永康市| 玉门市| 高州市| 依兰县| 贺兰县| 镇平县| 德令哈市| 临澧县| 治多县| 固阳县| 盈江县|