我已經編寫了一個自定義篩選器屬性來檢查每個控制器的動作,如果用戶有權訪問該操作,我給予訪問,否則我重定向到控制器未經授權的訪問,這裏是我的代碼:通過檢查訪問權隱藏ActionLinks的通用方法
public class AuthorizationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string actionName = filterContext.ActionDescriptor.ActionName;
string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
if (!CheckAccessRight(actionName, controllerName))
{
string redirectUrl = string.Format("?returnUrl={0}", filterContext.HttpContext.Request.Url.PathAndQuery);
filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl + redirectUrl, true);
}
else
{
base.OnActionExecuting(filterContext);
}
}
}
這裏是我的CheckAccessRight方法:
private bool CheckAccessRight(string Action, string Controller)
{
if (HttpContext.Current.Session["userId"] != null)
{
string userID = HttpContext.Current.Session["userId"].ToString();
using (var db = new cloud_clinicEntities())
{
assignment objAss = db.assignments.SingleOrDefault(model => model.userid == userID);
String UserRole = objAss.itemname;
itemchildren objChild = db.itemchildrens.SingleOrDefault(model => model.parent == UserRole && model.child == Controller + " " + Action);
if (objChild != null)
{
return true;
}
else
{
return false;
}
}
}
else
{
return false;
}
}
現在我想對我的每一個觀點,如果有操作鏈接到用戶無權訪問它不應該被網頁上呈現的控制器操作或者它應該被隱藏。如何以通用的方式做到這一點,我有想法,我可以通過在每個操作鏈接上添加if語句來實現,但我不認爲它是更好的方法。
的[基於角色的內容asp.net的MVC(http://stackoverflow.com/questions/928654/role-based-content-asp-net-mvc) –