当前位置:编程学习 > asp >>

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

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

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

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

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

补充:Web开发 , ASP.Net ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,