AOP (Aspect oriented programming)-oriented aspect programming, the main meaning is the same, similar and scattered logic out, unified processing, so not only to maintain the convenience, but also make the code more concerned about themselves, clear.
For example, our common permission checks, authentication login, exception handling and so on are scattered in various parts of the system, such as administrator in the login state can add a student information:
Public actionresult addstudent (Student Student) { ifnull) { Studentdal.add (student); } Else { //dosomething else } }
View Code
Originally a Studentdal.add (student) can be implemented function, but now to add if else, but also to deal with the exception, the code looks very ugly, if the following way:
[HttpPost] [authorize] public actionresult addstudent (Student Student) { Studentdal.add (student); return View (); }
View Code
This way of dealing with the problem with the Authroizeattribute feature is the idea of AOP, which not only makes the code clearer, but also allows the attribute to be reused.
attribute is just an implementation, and attribute is attribute by reflection before invoking a specific action, and then executing the code. Like verification login can be placed in the base class controller to make judgments, and some fine-grained permissions control We can customize the attribute to achieve.
Here is an example of exception handling, if there is a unified logic to handle the exception, then the logic code can be used without a try catch, but directly throw exception, will make the code more concise. (Not that there is a unified processing will not be used to catch, some exceptions or to capture, to see the specific business requirements, in addition to catch exceptions such as line thread to pay attention to catch).
Publicactionresult addstudent (Student Student) {if(string. IsNullOrEmpty (student. Name)) {Throw NewArgumentException ("name"); } returnView (); } protected Override voidonexception (Exceptioncontext filtercontext) {stringFilePath = 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
As long as you override the Onexception method in the controller, you can handle all of the exceptions in it, logging the Exception log (using log4net), jumping to a custom error page, and so on.
Of course, you can also customize the exception handling feature for action.
Public classExceptionlogfilterattribute:filterattribute, Iexceptionfilter { Public voidonexception (Exceptioncontext filtercontext) {stringFilePath =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