跟小D每日学口语

公司项目改进之权限篇[原创]

公司项目的权限写在page基类里,和页面紧耦合,每个页面都要去写下,权限设置,太过麻烦。

经过一些实验测试,Attribute和IHttpModule设计权限验证模块,还是比较不错。

我们公司的权限模块是写在枚举里的,设计一个Attribute类,里面放这个枚举:

[AttributeUsage(AttributeTargets.Class)]
public class SystemModuleAttribute : System.Attribute
{
    public SystemModuleList CurrentPageSystemModule { get; set; }
}

  

在页面的类上面添加这个属性:

 [SystemModule(CurrentPageSystemModule = SystemModuleList.PW_Members)]
 public partial class MemberEdit :  EMS.WebUtility.PageBase
 {
     //TODO:
 }

  

设计一个IHttpModule:

 public class PermissionsModule : IHttpModule
    {
        #region IHttpModule Members

        public void Init(HttpApplication context)
        {
            context.AcquireRequestState += new EventHandler(context_AcquireRequestState);
        }

        void context_AcquireRequestState(object sender, EventArgs e)
        {
            HttpApplication Application = (HttpApplication)sender;
            HttpContext context = (HttpContext)Application.Context;  

            if (Application.Request.Url.PathAndQuery.EndsWith("Login.aspx")) return;//排除一些页面

            PageBase pb = context.CurrentHandler as PageBase;//当前句柄(页面)

            if (pb != null)
            {
                Type t = pb.GetType();//获取元数据
                Object[] obj = t.GetCustomAttributes(typeof(SystemModuleAttribute), true);

                SystemModuleAttribute attr = null;
                foreach (SystemModuleAttribute att in obj)
                {
                    attr = att;
                }
                if (attr != null)
                {
                    SysID CurrentSystem = EMS.WebUtility.UserLoginAccount.GetCurrentUserBySession().UserCurrentSystem;
                    EMS.WebUtility.UserLoginAccount.NoModulePermissionsToRedirictErrorPage(CurrentSystem, attr.CurrentPageSystemModule);
                }
            }
        }

        public void Dispose()
        {
            
        }

        #endregion
    }

  

然后就可以把pagebase里的那些恶魔代码去掉。

Attribute是很强大的玩意,权限粒度细可以分到控件和方法(上面的方法仅限页面级别的)。

posted @ 2012-04-18 12:03  腐乳  阅读(373)  评论(1编辑  收藏  举报