ASP.NET MVC中权限控制的简单实现

来源:互联网 发布:淘宝客服在哪里应聘 编辑:程序博客网 时间:2024/04/27 21:55

1、重写AuthorizeAttribute类,用自己的权限控制逻辑重写AuthorizeCore方法

public class MyAuthorizeAttribute : AuthorizeAttribute     {        protected override bool AuthorizeCore(HttpContextBase httpContext)        {            string currentRole = (Session["user"] as User).Role;            //从Session中获取User对象,然后得到其角色信息。如果用户重写了Identity, 则可以在httpContext.Current.User.Identity中获取            if (Roles.Contains(currentRole))                return true;            return base.AuthorizeCore(httpContext);        }    }


2、在需要进行权限控制的Action上加上相应的Attribute,并且设置可以访问的角色组

 [MyAuthorize(Roles = "Admin, User")]        public ActionResult AuthorizeMethod2()        {            return View();        }

当用户访问相应的Action的时候,就会进行相应的权限控制。