ASP.NET MVC中有關AOP的編程

來源:互聯網
上載者:User

標籤: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

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.