ASP.NET本身擁有membership角色權(quán)限系統(tǒng),但是這個自帶的系統(tǒng)不夠靈活和強大,有時候操作起來比較繁瑣,這里方維網(wǎng)絡介紹一種如何根據(jù)控制器和方法自動判定權(quán)限,簡單方便。
首先是定義一個類繼承ActionFilterAttribute類,然后重新方法OnActionExecuting 編寫如下代碼
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
//沒有登錄執(zhí)行的操作
}
else
{
//判斷是否存在角色
FormsIdentity user = (FormsIdentity)HttpContext.Current.User.Identity;
var au = db.AdminUser.Where(a => a.username == user.Name).ToList();
if (au.Count > 0)
{
// string purview= au[0].group.purview;
bool is_authorize = true;
string error_msg = "沒有權(quán)限訪問!";
string model = filterContext.RouteData.Values["controller"].ToString();
string action = filterContext.RouteData.Values["action"].ToString();
BLLAdminUser admin_user = new BLLAdminUser();
string purview=admin_user.getCheckPurview(model, action);//判斷權(quán)限
string mypurview = admin_user.getMyPurview();
is_authorize=admin_user.inPurview(purview, mypurview);
if (!is_authorize)
{
//如果驗證不通過執(zhí)行的方法
}
}
}
}
然后在控制器或方法前面加上[Authorize]驗證標記就行了。