我一直都比較關注 功能項增、刪、改查許可權的解決方案 也看過園子裡一些園友的解決方案 可是一直都沒看到我期待的解決方案(也許是我沒看見)
前端時間看到一邊擴充的文章 頓時豁然開朗 想出了一種解決方案
功能描述
如:菜單管理 路徑為:/Back/Menu 我需要為這個頁面根據角色或個人等設定 增、刪、改許可權 下面就以角色為例(需判斷多個取並集)
我的解決方案:
首先用一個關係表 儲存菜單
菜單ID 角色ID 擁有許可權
1 1 ADD;EDIT;DEL
2 1 ADD
3 1 DEL
角色ID為1的使用者擁有 三個功能表項目的許可權 (許可權是根據一種約定設定 ADD為增加 EDIT為編輯 DEL為修改 可根據自己喜好設定)
擴充Html.ActionLink 方法 如:
using System.Web.Mvc.Html;using System.Web.Security;using IService;using Models;using System.Collections.Generic;using yujiajunMvc;using System.Linq;namespace System.Web.Mvc{ public static class HtmlExtensions { /// <summary> /// 判斷許可權串連 /// </summary> /// <param name="htmlHelper"></param> /// <param name="linkText">顯示的文字</param> /// <param name="operate">當前什麼操作 ADD添加 EDIT編輯 DEL刪除</param> /// <returns></returns> public static MvcHtmlString ActionLinks(this HtmlHelper htmlHelper, string linkText, string actionName, string controllName, object routeValues, object htmlAttributes, string operate) { HttpCookie cookie = HttpContext.Current.Request.Cookies["operateItem"];//在登入時儲存使用者權限 在此處擷取該使用者的許可權 if (cookie == null || string.IsNullOrEmpty(operate)) return MvcHtmlString.Empty; string path = HttpContext.Current.Request.RawUrl.ToLower();// 當前頁面路徑 List<string> list = DESEncrypt.Decrypt(cookie.Value).Split(',').ToList();//解密轉為字串 取得目前使用者的功能許可權此處我設定為 /Back/Menu/_ADD;EDIT,/Back/UserList/_EDIT;DEL 以此類推 此處注意mvc中路徑有些區別 如 /Back/Menu /Back/Menu/ 等都是訪問同一頁面 所以設定約定是需注意此處變化
var limit = list.FirstOrDefault(a => a.Contains(path));//如果當前頁面在 許可權能找到 if (limit != null) if (limit.Contains(operate)) //並且擁有傳遞進來的許可權 此處需和自己的約定一直 return htmlHelper.ActionLink(linkText, actionName, controllName, routeValues, htmlAttributes); //返回串連 return MvcHtmlString.Empty;//沒有許可權返回為空白 } public static MvcHtmlString ActionLinkEmpty(this HtmlHelper htmlHelper, string linkText, string operate, string property = null) { HttpCookie cookie = HttpContext.Current.Request.Cookies["operateItem"];//擷取該使用者的許可權 if (cookie == null || string.IsNullOrEmpty(operate)) return MvcHtmlString.Empty; string path = HttpContext.Current.Request.RawUrl.ToLower();//當前頁面路徑 List<string> list = DESEncrypt.Decrypt(cookie.Value).Split(',').ToList();//解密轉為字串 var limit = list.FirstOrDefault(a => a.Contains(path)); if (limit != null) if (limit.Contains(operate)) return MvcHtmlString.Create(string.Format("<a href=\"javascript:void(0)\" id=\"{0}\" class=\"{1}\" {2}>{3}</a>", operate, operate, property, linkText)); return MvcHtmlString.Empty; } }}
前台頁面調用
@Html.ActionLinks("添 加","UserADD","Items",null,null,"ADD")
這樣就實現了許可權判斷
此處還存在一個問題 一直沒想到好的解決方案 希望園友們能提供好的解決方案
當使用者直接在瀏覽器輸入時 在子頁面不好做許可權判斷 上面也提到了次問題
/Back/Menu/ADD /Back/Menu/ADD/ /Back/Menu/ADD/1
等都是訪問同一頁面 所以不好根據路徑判斷