標籤:style class blog code http ext
看了一些關於這方面的文檔,自我總結:
特性(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; } }
感覺這個違背了特性的設計初衷啊