標籤:style blog http color os io
AOP(Aspect oriented programming)面向切面編程,主要意思是把相同、相似的並且零散的邏輯抽離出來,統一處理,這樣不僅維護起來方便,也使得代碼更加關注自己本身,清晰明了。
比如我們常見的許可權檢查,驗證登陸,異常處理等都是散亂在系統各個地方,比如管理員在登陸狀態才可以添加一個學生資訊:
public ActionResult AddStudent(Student student) { if (currentUser != null) { StudentDAL.Add(student); } else { //do something else } } View Code
本來一句StudentDAL.Add(student)就可以實現的功能,現在卻要加上if else,還要處理異常,代碼顯得很難看,如果採用如下的方式:
[HttpPost] [Authorize] public ActionResult AddStudent(Student student) { StudentDAL.Add(student); return View(); }View Code
這種用AuthroizeAttribute特性來處理問題的方式,就是AOP的思想,不僅使代碼更加清晰,而且還可以複用這個Attribute。
Attribute只是一種實現方式,Attribute也是在調用具體的action前,通過反射得到Attribute,然後執行代碼。像驗證登陸可以放在基類Controller中去做判斷,而一些細化的許可權控制我們可以自訂Attribute來實現。
下面是一個異常處理的例子,如果有一個統一的處理異常的邏輯,那麼邏輯代碼裡就可以不用try catch,而是直接throw exception,會讓代碼更簡潔。(並不是說有了統一處理就再不用try catch了,有些異常還是要去捕獲,看具體業務需求,另外捕獲不到異常的比如線程裡的要注意catch)。
public ActionResult AddStudent(Student student) { if (string.IsNullOrEmpty(student.Name)) { throw new ArgumentException("name"); } return View(); } protected override void OnException(ExceptionContext filterContext) { string filePath = Server.MapPath("~/exception.txt"); using (StreamWriter writer = System.IO.File.AppendText(filePath)) { writer.WriteLine(filterContext.Exception.Message); } base.OnException(filterContext); Response.Redirect("~/Error/NotFound"); }View Code
只要在Controller中重寫OnException方法就可以處理該控制器中所有的異常,實現記錄異常日誌(利用Log4Net),跳轉到自訂錯誤頁面等。
當然也可以自訂針對Action的異常處理特性。
public class ExceptionLogFilterAttribute : FilterAttribute, IExceptionFilter { public void OnException(ExceptionContext filterContext) { string filePath =HttpContext.Current.Server.MapPath("~/exception.txt"); using (StreamWriter writer = System.IO.File.AppendText(filePath)) { writer.WriteLine(filterContext.Exception.Message); } HttpContext.Current.Response.Redirect("~/Error/NotFound"); } }View Code