自定义特性用途---案例:操作权限
发表于:2024-11-29 作者:热门IT资讯网编辑
编辑最后更新 2024年11月29日,--------------------------------------------------LimitAttribute.cs 自定义特性using System;using System.C
--------------------------------------------------LimitAttribute.cs 自定义特性
using System;using System.Collections.Generic;using System.Linq;using System.Web;////// LimitAttribute 的摘要说明/// //特性只作用与方法上[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) { } ////// 判断该用户是否有执行权限 /// /// 用户名称 /// 方法名称 ///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); } }}