基於頁面的權限設計原形

權限屬性定義:安全

/// <summary>
    /// 權限屬性
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    public class AccessLevAttribute : Attribute
    {
        /// <summary>
        /// 名稱
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 權限
        /// </summary>
        public string LevStr { get; set; }

        /// <summary>
        /// 
        /// </summary>
        static Type attrType = typeof(AccessLevAttribute);

        public AccessLevAttribute(string name)
        {
            this.Name = name;
        }

        public AccessLevAttribute(string name, string levStr)
        {
            this.Name = name;
            this.LevStr = levStr;
        }

        /// <summary>
        /// 解析類屬性
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static AccessLevAttribute ParseClass(Type t)
        {
            return Parse(t.GetCustomAttributes(attrType, false));
        }

        /// <summary>
        /// 解析方法屬性
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public static AccessLevAttribute ParseMethod(MethodInfo m)
        {
            return Parse(m.GetCustomAttributes(attrType, false));
        }

        static AccessLevAttribute Parse(object[] attributes)
        {
            return (attributes == null || attributes.Length != 1) ? null : attributes[0] as AccessLevAttribute;
        }
    }

 

 

頁面基類:this

public class PageBase : System.Web.UI.Page
    {
        public PageBase()
        {
            this.Init += new EventHandler(PageBase_Init);
        }

        void PageBase_Init(object sender, EventArgs e)
        {
            Type clssType = this.GetType().BaseType;

            var classAttr = AccessLevAttribute.ParseClass(clssType); //獲取類上定義的權限數據
            Response.Write(classAttr == null ? clssType.Name : classAttr.Name);
                        
            foreach (var m in clssType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
            {
                var a = AccessLevAttribute.ParseMethod(m); //獲取方法上定義的權限數據
                Response.Write(a == null ? m.Name : a.Name);
            }
            
        }
    }

 

頁面類:url

[AccessLev("classAliasName")]
    public partial class WebForm1 :PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [AccessLev("methodAliasName")]
        string Test()
        {
            return DateTime.Now.ToString();
        }
    }

 

驗證在基類中統一完成,相對通常的基於url驗證更安全,且可細化到頁面的方法級orm

相關文章
相關標籤/搜索