--------------------------------------------------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); } } }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。