看了一些关于这方面的文档,自我总结:
特性(Attribute)就是对一个方法或类做的一个额外的属性说明,也就是附加说明
下面是我自己抄的一个实例程序:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace SomeTest { class Program { static void Main(string[] args) { demo d = new demo(); string username = "Lucy"; MethodInfo mi = d.GetType().GetMethod("Test"); if (mi == null) return; AllowExecuteAttribute att = Attribute.GetCustomAttribute(mi,typeof(AllowExecuteAttribute)) as AllowExecuteAttribute; if (att == null) return; if (att.Check(username)) Console.WriteLine("允许执行"); else Console.WriteLine("不允许执行"); Console.ReadKey(); } } class demo { [AllowExecute("jack,Tom")] public void Test() { } } /// <summary> /// 标识某方法允许执行的用户 /// </summary> public class AllowExecuteAttribute : Attribute { /// <summary> /// /// </summary> /// <param name="allowedUsers">允许执行的用户名的串联字符串</param> public AllowExecuteAttribute(string allowedUsers) { this._allowedUsers = allowedUsers; } private string _allowedUsers; public bool Check(string userName) { return this._allowedUsers.ToLower().IndexOf(userName.ToLower()) > -1; } } }
下面是公司项目中MVC中对AuthorizeAttribute特性的一些使用方法:
public class SingleUserAuthorize : AuthorizeAttribute { [ValidateInput(false)] protected override bool AuthorizeCore(HttpContextBase httpContext) { Hashtable userOnline = (Hashtable)(httpContext.Application["Online"]); if (userOnline != null) { IDictionaryEnumerator idE = userOnline.GetEnumerator(); string strkey = string.Empty; if (userOnline.Count > 0) { while (idE.MoveNext()) { //登录时判断保存的session是否与当前页面的session相同 if (userOnline.Contains(httpContext.Session.SessionID)) { if (idE.Key != null && idE.Key.ToString().Equals(httpContext.Session.SessionID)) { //判断当前session保存的值是否为被注销值 if (idE.Value != null && "XXXXXX".Equals(idE.Value.ToString())) { //验证被注销则清空session userOnline.Remove(httpContext.Session.SessionID); httpContext.Application.Lock(); httpContext.Application["Online"] = userOnline; httpContext.Response.Write("<script>top.location.href=‘/Home/Message?message=offline‘;</script>"); httpContext.Response.End(); return false; } } } else { return false; } } return true; } else { return false; } } return false; } }
感觉这个违背了特性的设计初衷啊