Source: Internet
Author: User
I. What is AOP?

AOP(Aspect-Oriented Programming, Aspect-Oriented Programming) can be said to be a supplement and improvement of OOP (object-oriented programing, object-oriented programming. Oop introduces concepts such as encapsulation, inheritance, and Polymorphism to establish an object hierarchy to simulate a set of public behaviors. When we need to introduce public behavior to scattered objects, oop seems powerless. That is to say, oop allows you to define the relationship from top to bottom, but it is not suitable for defining the relationship from left to right. For example, log function. LogsCodeIt is often horizontally distributed across all object layers, but it has nothing to do with the core functions of the objects it spreads. This is also true for other types of code, such as security, exception handling, and transparent persistence. This unrelated code distributed everywhere is called cross-cutting code. in OOP design, it leads to a large number of code duplication, which is not conducive to the reuse of each module.

The AOP technology is the opposite. It uses a technology called "cross-cutting" to segment the encapsulated object, encapsulate the public behaviors that affect multiple classes into a reusable module and name it "aspect", that is, aspect. The so-called "aspect" is simply to encapsulate the logic or responsibilities that are irrelevant to the business but are called by the business module to reduce repeated system code, reduce the coupling between modules and facilitate future operability and maintainability. AOP represents a horizontal relationship. If "object" is a hollow cylinder that encapsulates the attributes and behaviors of objects, then the method for Aspect-Oriented Programming is, it is like a sharp blade that splits these hollow cylinders to obtain internal messages. The cut section is the so-called "aspect. Then it restored these cut sections with the skill of winning the power of heaven without leaving any trace.

Using the "cross-cutting" technology,AOP divides the software system into two parts: core focus and cross-cutting focus..The main process of business processing is the core focus, and the part that has little to do with it is the cross-cutting focus. One feature of cross-cutting concerns is that they often occur in multiple places of core concerns, and are similar everywhere. For example, permission authentication, logs, and transaction processing. The function of AOP is to separate the various concerns in the system from the core concerns and the cross-cutting concerns. As Adam Magee, Senior Solution Architect at avanade, said,The core idea of AOP is to "applyProgramThe business logic in is separated from the general services that it provides support ."

The technology for Implementing AOP is mainly divided into two categories: one is to use dynamic proxy technology, and use the method of intercepting messages to describe the message to replace the execution of the original object behavior; the second is to use static weaving to introduce specific syntax to create "aspect", so that the compiler can weave "aspect" code during compilation. However, the same way is achieved, and the technical features for Implementing AOP are the same:

1,Join point): Is an exact execution point in program execution, such as a method in the class. It is an abstract concept. When Implementing AOP, you do not need to define a join point.
2,Point cut): Essentially a structure that captures the connection points. In AOP, you can define a point cut to capture calls to related methods.
3,Advice (Notification): It is the Execution Code of point cut and the specific logic of executing "aspect.
4,Aspect (aspect): Point cut and advice are combined with aspect. It is similar to a class defined in OOP, but it represents more of a horizontal relationship between objects.
5,Introduce (introduced): Introduce additional methods or attributes to the object to modify the object structure. Some AOP tools call it Mixin.

The above technical features constitute the basic AOP technology, which is implemented by most AOP tools. They can also be the basic term for studying AOP technology.

 Cross-cutting technology

"Cross-cutting" is a special term of AOP. It is a relatively simple design and programming technology with powerful power, especially when it is used to build loosely coupled, scalable enterprise systems. The cross-cutting technique allows AOP to traverse established responsibilities (such as logging and performance optimization) in a given programming model.

If no cross-cutting technology is used, what is the situation of software development? In traditional programs, because the implementation of cross-cutting behaviors is scattered, it is difficult for developers to implement or change these behaviors logically. For example, the code used for logging and the Code primarily used for other duties are intertwined. Depending on the complexity and scope of the problem to be solved, the confusion may be large or small. Changing the logging policy for an application may involve hundreds of edits-even if feasible, This is a headache.

In AOP, we call these actions with public logic entangled with the core logic of other modules "crosscutting concern )", it spans the typical responsibility boundaries of a given programming model.


A concern is a specific purpose, a region we are interested in, and a logical action we need. From a technical point of view, a typical software system includes some core points of attention and system-level concerns. For example, a credit card processing system focuses on lending/deposit processing, while the system focuses on logs, transaction integrity, authorization, security, and performance, many concerns-that is, crosscutting concerns-will appear in multiple modules. If the existing programming method is used, the cross-cutting concerns will jump across multiple modules, making it difficult for the system to design, understand, implement, and evolve. Compared with the preceding method, AOP can better isolate system concerns and provide modular cross-cutting concerns.

For exampleA complex system is implemented by a combination of multiple concerns, such as business logic, performance, data storage, logs and scheduling information, authorization, security, threads, and error checks, there are also concerns in the development process, such as easy to understand, easy to maintain, easy to trace, and easy to expand.Figure 2.1 demonstrates a system composed of a group of concerns implemented by different modules.

Figure 2.1 implement the module as a group of concerns

By identifying system requirements and implementation, we can divide these concerns in the module into core concerns and cross-cutting concerns. For core concerns, the modules that implement these concerns are independent of each other. They fulfill the business logic required by the system, which is related to specific business needs. But for the log, security, persistence and other concerns, they are the common needs of the business logic module, these logics are distributed in the core focus. In AOP, such modules are called cross-cutting concerns. The key to applying the cross-cutting technology of AOP is to recognize the concerns.

If the entire module is compared to a cylinder, the focus recognition process can be described by the prism rule. The beam passing through the prism (as required) can be illuminated everywhere in the cylinder to obtain different colors of the beam, at last, different concerns are identified. 2.2:

Figure 2.2 attention recognition: prism rule

Among the identified concerns, business logic is the core concern. It calls security, logging, persistence, and other cross-cutting concerns.

Public class businesslogic
Public void someoperation ()
// Verify security; securtity considerations;
// Logs are recorded before execution; Logging concerns;

Dosomething ();

// Save the data after the logical operation; persistence focus;
// Logs of execution end records; Logging concerns;

The purpose of AOP is to separate cross-cutting concerns such as logging from the businesslogic class. The AOP technology can be used to encapsulate related cross-cutting concerns to form a separate "aspect ". This ensures the reuse of cross-cutting concerns. Because the businesslogic class no longer contains the logic code of the Cross-concern, to call the cross-concern, you can use the cross-concern technology to intercept messages of relevant methods in the businesslogic class, such as the someoperation () method, then these "aspect" are woven into this method. Example 2.3:

Figure 2.3 resolve a cross-cutting concern to the core concern

By using the AOP technology, the design of the entire system is changed. At the beginning of analyzing system requirements, the idea of AOP is used to separate core points of concern and cross-cutting concerns. After implementing the general logic of cross-concern such as logs, transaction management, and permission control, developers can focus on their core concerns and focus on solving their business logic. At the same time, the functions provided by these encapsulated cross-cutting concerns can be used to restore all parts of the business logic to the maximum extent, without the need for special coding by developers, it also does not affect the specific business functions because of the function of modifying the cross-concern.

To establish a loosely coupled and scalable enterprise system, AOP applies two types of cross-cutting technology: Dynamic cross-cutting and static cross-cutting. For details, refer to the AOP technical basics.

2. AOP implementation in MVC

Filter is the implementation of AOP

Sometimes you want to process some logic before or after calling the action method. To support this, ASP. net mvc allows you to create an action filter. The action filter is a custom attributes used to mark the actions before or after the action method is added to the Action Method in the Controller class.

Some places that may use the action filter include:

    • Log, Exception Handling
    • Authentication and authorization-restrict user access
    • Output cache-Save the result of an action
    • Web Crawler Filtering
    • Localization
    • Dynamic Action-inject an action into the Controller


ASP. net mvc provides the following filter interfaces:

    • Iactionfilter
    • Iauthorizationfilter
    • Iexceptionfilter
    • Iresultfilter

To implement a filter, We need to inherit fromFilterattributeClass simultaneously implements one or more of the above interfaces:

Public   Class Myfilter: filterattribute, iactionfilter, iresultfilter


These interfaces provide the following methods:

The method and the method corresponding to the filter interface can be seated by the name pair number.

IactionfilterThe interface has two methods:

Onactionexecuting is called before the action method is executed (pre-notification in AOP), and onactionexecuted is called after the action method is executed (post-notification in AOP ). Note that their parameters are actionexecutIngContext and actionexecutEdContext.

ActionexecutEdThe context class containsCanceledAllows you to cancel the current action.IngContextCanceledWhat if the attribute is missing in P5? Magic. How can I cancel an action during onactionexecuting ?).

FilterexcutEdThe context class contains an exception attribute and an exceptionhandled attribute. If the exception attribute is null, no exception is found in action stack, indicating that the action method has not encountered an error. Otherwise, an exception occurs. If you set the exceptionhandled attribute to true, it indicates that an exception has been processed in the filter.

The iresultfilter interface also provides two methods:

They are executed before and after the return result (for example, return view ();) of the action. AndIactionfilterI will not say much about it.

IauthorizationfilterIs a filter used for identity authentication. Only one void onauthorization (authorizationcontext filtercontext) method is provided.

IexceptionfilterIt is called when an exception occurs. It also provides only one void onexception (exceptioncontext filtercontext) method;

These filters can be applied to classes or methods. Let's take a look at their execution sequence. First, write a basecontroller and add two filters:

[Myfilter2 (Target =   " Basecontroller " )]
[Myfilter1 (Target = " Basecontroller " )]
Public   Class Basecontroller: Controller


This should be because the Controller class implements these filter interfaces, So we re-write all the filter interfaces in the controller base class in homecontroller, add the custom myfilter in the homecontroller class and the filter method in it:

[Myfilter2 (Target =   " Homecontroller " )]
// [Myfilter1 (target = "homecontroller")] // Note that I have commented out myfilter1 here.
Public   Class Homecontroller: basecontroller
[Myfilter2 (Target =   " Homecontroller. Filter " )]
[Myfilter1 (Target =   " Homecontroller. Filter " )]
Public Actionresult filter ()
Return Content ( " <Div> This is the content returned in the Action method! </Div> " );

Protected Override VoidOnactionexecuted (actionexecutedcontext filtercontext)
Filtercontext. httpcontext. response. Write ("<Div> This is the content added by rewriting the onactionexecuted method in homecontroller! </Div>");

Protected Override VoidOnactionexecuting (actionexecutingcontext filtercontext)
Filtercontext. httpcontext. response. Write ("<Div> This is the content added by rewriting the onactionexecuting method in homecontroller! </Div>");

Protected Override VoidOnauthorization (authorizationcontext filtercontext)
Filtercontext. httpcontext. response. Write ("<Div> This is the content added by rewriting the onauthorization method in homecontroller! </Div>");

protected override void onexception (exceptioncontext filtercontext)
{< br> filtercontext. httpcontext. response. write ( "

This is the content added by rewriting the onexception method in homecontroller!
" );
filtercontext. predictionhandled = true ;

Protected Override VoidOnresultexecuted (resultexecutedcontext filtercontext)
Filtercontext. httpcontext. response. Write ("<Div> This is added by rewriting the onresultexecuted method in homecontroller! </Div>");

Protected Override VoidOnresultexecuting (resultexecutingcontext filtercontext)
Filtercontext. httpcontext. response. Write ("<Div> This is the content added by rewriting the onresultexecuting method in homecontroller! </Div>");

Run the following command to check the result:

From the running results, we can see that the filter that is rewritten in the Controller will be first executed, then applied to the filter on the class, and then applied to the filter on the class method.

The execution sequence of the four interfaces is as follows:Iauthorizationfilter->Iactionfilter-> Iresultfilter-> Iexceptionfilter.

For the same filter, for exampleThe implementation of iauthorizationfilter in myfilter1 and myfilter2 varies according to their loading sequence.

The filter applied in basecontroller inherits the quilt class. If the subclass applies the same filter as the base class, the filter of the base class is not executed. For example, the preceding homecontroller applies myfilter2, so it calls myfilter2 of homecontroller instead of myfilter2 of basecontroller.

This execution sequence can only be understood after a good study.

Filterattribute also provides an order attribute to specify the execution sequence of the filter.

Each action filter has an order attribute to determine the execution sequence of the Action filter in this range. The Order attribute must be 0 (default) or a greater integer. If the order attribute is omitted, the order value of the filter is-1, indicating that the order is not specified. Any action filter whose order is set to-1 in the same range will be executed in an uncertain order, but before that, the filter has a specific order (SEE ).

When setting the value of the Order attribute, you must specify a unique value. If two or more action filters have the same order attribute value, an exception is thrown.

Let's look at an example:

[Filter1 (Order =   2 )]
[Filter2 (Order =   3 )]
[Filter3 (Order =   1 )]
Public   Void Index ()
Renderview ( " Index " );


Filter execution sequence: filter3 => filter1 => filter2. reference: ASP. net mvc entry 9. Action filter and built-in filter implementation (Introduction)

ASP. NET mvc3 global Filter

ASP. net mvc supports descriptive application of the "cross-cutting" logic through filtering. You can use the attribute syntax to specify filters for controllers and execution functions, as shown below:

But in use, we often want to apply some filter logic to all controllers in the program, such as the authorize filter.

Now ASP. NET mvc3 allows you to specify a global filter, which can be applied to all controllers in the program.

As shown in: add the custom filter to globalflitercollection in the Global File.

In mvc3, the judgment logic of this filter is very flexible. You can configure a global filter to enable it only when certain conditions are met.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

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.