MVC5中Filter控制Action的访问权限_Asp.Net MVC Filter权限过滤
2018-06-26 15:44:16  By: shinyuu

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


若资源对你有帮助、浏览后有很大收获、不妨小额打赏我一下、你的鼓励是维持我不断写博客最大动力

想获取DD博客最新代码、你可以扫描下方的二维码、关注DD博客微信公众号(ddblogs)

或者你也可以关注我的新浪微博、了解DD博客的最新动态:DD博客官方微博(dwtedx的微博)

如对资源有任何疑问或觉得仍然有很大的改善空间、可以对该博文进行评论、希望不吝赐教

为保证及时回复、可以使用博客留言板给我留言: DD博客留言板(dwtedx的留言板)

感谢你的访问、祝你生活愉快、工作顺心、欢迎常来逛逛


快速评论


技术评论

  • 该技术还没有评论、赶快抢沙发吧...
DD记账
top
+