--------------------------------------------------LimitAttribute.cs 自定义特性
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// LimitAttribute 的摘要说明 /// </summary> //特性只作用与方法上 [AttributeUsage(AttributeTargets.Method)] public class LimitAttribute:Attribute { private string _name; public string Name { get { return _name; } } public LimitAttribute(string name) { this._name = name; } }
--------------------------------------------------Default.aspx
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Reflection; public partial class _Default : System.Web.UI.Page { public static readonly string _name = "李四"; protected void Page_Load(object sender, EventArgs e) { } /// <summary> /// 判断该用户是否有执行权限 /// </summary> /// <param name="name">用户名称</param> /// <param name="method">方法名称</param> /// <returns></returns> private bool IsLimit(string name, string method) { //获取该类型 Type t = typeof(_Default); //查找该方法 MethodInfo mi = t.GetMethod(method); if (mi == null) return false; //获取方法上的特性 LimitAttribute la = Attribute.GetCustomAttribute(mi, typeof(LimitAttribute)) as LimitAttribute; if (la == null) return false; //判断用户 if (la.Name == name) { return true; } else { return false; } } [Limit("张三")] public void btnView_Click(object sender, EventArgs e) { if (IsLimit(_name, "btnView_Click")) { ClientScript.RegisterStartupScript(this.GetType(), "ClientScript", "alert(‘我是查看‘)", true); } else { ClientScript.RegisterStartupScript(this.GetType(), "ClientScript", "alert(‘对不起,您没有权限操作‘)", true); } } [Limit("李四")] public void btnEdit_Click(object sender, EventArgs e) { if (IsLimit(_name, "btnEdit_Click")) { ClientScript.RegisterStartupScript(this.GetType(), "ClientScript", "alert(‘我是修改‘)", true); } else { ClientScript.RegisterStartupScript(this.GetType(), "ClientScript", "alert(‘对不起,您没有权限操作‘)", true); } } [Limit("李四")] public void btnAdd_Click(object sender, EventArgs e) { if (IsLimit(_name, "btnAdd_Click")) { ClientScript.RegisterStartupScript(this.GetType(), "ClientScript", "alert(‘我是添加‘)", true); } else { ClientScript.RegisterStartupScript(this.GetType(), "ClientScript", "alert(‘对不起,您没有权限操作‘)", true); } } [Limit("王五")] public void btnDel_Click(object sender, EventArgs e) { if (IsLimit(_name, "btnDel_Click")) { ClientScript.RegisterStartupScript(this.GetType(), "ClientScript", "alert(‘我是删除‘)", true); } else { ClientScript.RegisterStartupScript(this.GetType(), "ClientScript", "alert(‘对不起,您没有权限操作‘)", true); } } }
本文出自 “程序猿的家--Hunter” 博客,请务必保留此出处http://962410314.blog.51cto.com/7563109/1571852
原文:http://962410314.blog.51cto.com/7563109/1571852