权限属性定义:
/// <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; } }
页面基类:
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); } } }
页面类:
[AccessLev("classAliasName")] public partial class WebForm1 :PageBase { protected void Page_Load(object sender, EventArgs e) { } [AccessLev("methodAliasName")] string Test() { return DateTime.Now.ToString(); } }
验证在基类中统一完成,相对一般的基于url验证更安全,且可细化到页面的方法级
时间: 2024-11-06 23:22:04