MVC 5 中Filter控制 action的访问权限
1,创建一个继承自 FilterAttribute, IActionFilter的类
namespace HeatMetering2.Filters { public class HMV2AuthenticationAttribute : FilterAttribute, IActionFilter { int notAuthentication = 0; //设置未认证标志,用于区分返回不同的未认证页面 public void OnActionExecuted(ActionExecutedContext filterContext) { } public void OnActionExecuting(ActionExecutingContext filterContext) { //if (true) //{ // // 已登录,并且查询数据库后具有操作权限或者设置了Anonymouse,以及当前用户是admin //} //else //{ // context.Result = new HttpUnauthorizedResult(); // mark unauthorized //} notAuthentication = 0; if (notAuthentication == 0 && filterContext.ActionDescriptor.ControllerDescriptor.ControllerName == "basLoginUsers" && filterContext.ActionDescriptor.ActionName == "EditBasLoginUser") { filterContext.Result = new RedirectToRouteResult("Default", new System.Web.Routing.RouteValueDictionary{ {"controller", "Account"}, {"action", "NotAuthentication"}, {"returnUrl", filterContext.HttpContext.Request.RawUrl} }); } } } }
2,在controller中这样引用该类
[HMV2Authentication] public class basLoginUsersController : Controller { private HeatMeteringV2DBContext db = new HeatMeteringV2DBContext("HeatMeteringV2DBContext"); // GET: basLoginUsers public ActionResult Index() { return View(); } public ActionResult EditBasLoginUser(basLoginUser _basLoginUser) { if (ModelState.IsValid) { try { db.Entry(_basLoginUser).State = EntityState.Modified; string _password = _basLoginUser.Password; //随机 "盐",生成自GUID string salt = Guid.NewGuid().ToString(); string strPasswordHash = CommFunc.GetPasswordEncryptByHashWithSalt(_password, salt); _basLoginUser.PasswordHash = strPasswordHash; _basLoginUser.PasswordSalt = salt; db.SaveChanges(); var json = new { okMsg = "修改成功" }; return Json(json, "text/html", JsonRequestBehavior.AllowGet); } catch(Exception ex) { var json = new { errorMsg = "保存数据出错:"+ex.Message.ToString() }; return Json(json, "text/html", JsonRequestBehavior.AllowGet); } } else { var json = new { errorMsg = "验证错误" }; return Json(json, "text/html", JsonRequestBehavior.AllowGet); } } }
3,在Account controller中定义如下Action,这样引用basLoginUsersController 的EditBasLoginUser 这个Action都会被提示当前用户没有此项操作权限,
这里仅仅举了个例子,再实际应用中我们可以在我们定义的类的OnActionExecuting方法里面获取我们已经设定好的对controller->action的权限设定,来决定是否禁用该Action,以达到设定权限的目的。但是这样做的不好之处是,用户仍然可以执行操作,只是我们在用户操作以后才可以告诉用户啥啥不能用种种,有点不好。
目前想到的方法是在页面上用Ajax请求权限数据,利用Javascript(Jquery)来利用元素ID选择器选择操作元素,并且使元素不可操作/编辑
[AllowAnonymous] public ActionResult NotAuthentication() { var json = new { errorMsg = "当前用户没有此项操作权限" }; return Json(json, "text/html", JsonRequestBehavior.AllowGet); }