Using the Micrisoft.net Design Scenario Chapter III Web presentation mode Web mode cluster details intercepting filter (intercept filter)

Source: Internet
Author: User
Tags wrappers

intercepting Filter (Intercept filter)

We need more control when building a Web application, or we need to insert our own business logic before or after a Web request.

How do you implement common preprocessing and post-processing steps around Web page requests?

There are a number of ways to resolve this issue, so you need to consider which factors and tradeoffs are involved:

A, it is common practice to separate lower-level features (such as handling HTTP headers, cookies, or character encodings) from the application logic, which helps limit the proliferation of changes.

B, many preprocessing and post-processing tasks are common to all Web pages, and should be implemented in a central location to avoid code duplication.

C, many lower-level functions do not depend on each other, so that they do not affect each other

D. Ability to add or remove modules at deployment time and not compile

E, each module can be combined with each other

Solution Solutions

Create a string of composable filters to implement common preprocessing and post-processing tasks during WEB page requests.

Figure 1: a series of composable filters

Filters form a series of stand-alone modules that can be chained together to perform a common set of processing steps before the page request is passed to the controller object. Because each filter implements exactly the same interface, there is no explicit dependency between them. Therefore, you can add a new filter without affecting existing filters. method is to instantiate them dynamically based on the configuration file.

Filter Chain

The direct implementation of the intercepting filter is a chain of filters that can be used to traverse a list of all filters. The WEB request handler executes the filter chain first before passing control to the application logic.

When the WEB server receives a page request, the request handler first passes control to the Filterchain (filter chain) object. This object maintains a list of all filters, and invokes each filter sequentially. Filterchain can read the filter order from the configuration file to achieve the composable nature of the deployment. Each filter has the opportunity to modify the incoming request. For example, it can modify the URL, or add the header field to be used by the application. After all filters are executed, the request handler passes control to the controller, which executes the application functionality

Figure 3:intercepting Filter sequence diagram

Decorator

An interesting alternative to the intercepting Filter mode is to use the Decorator mode to wrap the Front Controller. Decorator can wrap an object so that it provides the same interface as the original object. Therefore, this wrapper is transparent to any other object that references the original object. Because the interface and wrapper for the original object are identical, you can add additional wrappers to wrap the wrapper to create a wrapper chain that is similar to the filter chain. Within each wrapper, preprocessing and post-processing functions can be performed.

Shows how to implement intercepting Filter using this concept. Each filter implements the Controller interface. It also includes a reference to the next object that implements the Controller interface, which may be the actual controller (Concretecontroller) or another filter. Instant filters can be called each other, and there is no direct dependency between the filters, because each filter references only the Controller interface, not the next filter class.

It has the opportunity to perform preprocessing tasks before the filter passes control to the next filter. Similarly, the filter has an opportunity to perform post-processing tasks after the remaining filters in the filter chain have finished processing the request.

Event-Driven filters

This model has some similarities to the event model described in Observer mode. In both cases, the object can "subscribe" to the event if the original object does not depend on the observer. The object does not depend on any particular observer, because it invokes the observer through an abstract interface. The main difference between intercepting filter and Observer is that observers typically do not modify the source object, but passively "observe" the events that occur in the source object. On the other hand, the purpose of the intercepting Filter is to intercept and modify the context in which it is invoked. It also provides a good illustration of how each filter intercepts the sequence of events within the WEB server framework.

Variant

In most cases, the filter is passive in this sense because the filter operates the context but does not affect the execution flow. However, if a filter intercepts WEB requests, you will typically have to design the filter to redirect requests to other pages. For example, if validation fails, the validation filter may redirect the request to the error page or to the login page.

To demonstrate how these filters affect the flow of WEB requests, a typical sequence of filter scenarios is displayed, in which the interception filter does not interfere with the message flow.

Interception filters that do not interfere with the message flow

Displays an alternate sequence where Filter one redirects the message flow to another page based on the type of request.

Intercepting filters for redirecting message flows

In this scenario, no page is rendered, but a redirect header (HTTP response 302) is generated and returned to the client. This header information causes the client to issue a new request to the URL specified in the redirect header. Because this type of redirection requires another request from the client browser, it is often referred to as client redirection. The main drawback is that the client browser must issue two requests to retrieve the page. This slows down the page display and complicates the bookmarks because the client creates bookmarks for the redirected URLs, which is usually not good.

On the other hand, server end multiplicity orientation forwards requests to other pages without requiring a round trip to the client. They do this by returning control to the HttpRunTime object, and the HttpRunTime object calls the other page Controller directly along the request context. This delivery occurs inside the server and does not involve the client. Therefore, you do not have to repeat any public preprocessing tasks on the request.

Server end multiplicity targeting is used in two common scenarios: You can use URL actions in the intercepting Filter to allow clients to pass parameters to the application using a virtual URL. Another common approach is to use the Front Controller. The Front controller processes all page requests in a central component, and then passes control to the appropriate command. The Front Controller is useful if the WEB application has a dynamically configurable navigation path.

The intercepting Filter mode has the following advantages and disadvantages:

Advantages

1. Separation of tasks. The logic contained in the filter is separated from the application logic. Therefore, application code is not affected when low-level functionality changes (for example, if you migrate from HTTP to HTTPS, or if you migrate session management from URL rewriting to hidden form fields).

2, flexibility. Individual filters are independent of each other. Therefore, you can link any combination of filters without having to make code changes to any filters.

3, the central configuration. Because filters are composable, you can use a single configuration file to load the filter chain. You can modify a single configuration file to determine which filter list to insert into the request processing without using many source code.

4, the deployment of composable. At run time, the intercepting Filter chain can be constructed from the configuration file. Therefore, you can change the order of the filters during deployment without having to modify the code.

5. Re-usability. Because filters do not depend on their operating environment (except for the context in which they operate), you can reuse individual filters in other Web applications.

Disadvantages

1, sequential dependence. The interception filter does not explicitly depend on any other filters. However, filters can assume the context-sensitive information that is passed to them. For example, some filters might expect some processing to occur before they are called. Consider these implicit dependencies when you configure the filter chain. Some frameworks may not guarantee the order of execution between filters. Hard-coded method calls may be better than dynamic filter chains if the program requires a strict order.

2, sharing status. In addition to the operation context, filters do not have an explicit mechanism for sharing state information with each other. This is also true for passing information from the filter to another filter. For example, if the filter parses the browser type based on the value of the header field, you cannot simply pass this information to the application controller. The most common way to do this is to add a dummy header field to the request context that contains the filter output. The controller can then extract the dummy header field and make a decision based on its value. Unfortunately, you lose any compile-time checks or type safety between the filter and the controller. This is an unfavorable aspect of loose coupling.

Intercepting filters and controllers

Because interception filters are executed just before and after the controller, it can sometimes be difficult to determine whether the functionality is implemented within the interception filter or within the controller. The following guidelines provide some guidance for making this decision:

Filters are more suitable for handling low-level functions related to transport, such as character set decoding, decompression, session validation, client browser type recognition, and traffic logging. These types of operations are often packaged in a good, efficient, stateless state. Therefore, it is easy to link these operations together, and one operation does not necessarily pass state information to another operation.

Real-world application functionality that interacts with the model is best implemented within a controller or controller helper. These types of features typically do not have the kind of composable that a filter requires.

In most cases, processing inside the filter does not depend on the state of the application; Even if the page controller may contain common functionality, it is a good idea to preserve the opportunity to overwrite behaviors individually. The controller is more suitable for this task than the filter chain.

Many filter implementations (for example, IIS ISAPI filters) are executed at a lower level within the application server. This gives the filter a lot of control (not many events occur before the filter is called), but it prevents them from accessing many of the features offered by the application layer, such as session management.

Because filters are executed for each WEB page request, performance is critical. Therefore, the framework may limit the choice of the implementation language. For example, most ISAPI filters are implemented using compiled languages such as C + +. If you have easy access to Microsoft Visual basic® development system or Microsoft Visual c#® Development tools to write this code, and to have complete access to the. NET Framework, you do not have to use C + + to write code for complex application logic.

in the ASP . using HTTP in module Implementation intercepting Filter

Microsoft ASP uses many different types of requests to build Web applications. Some requests are transferred to the appropriate Web page, and other requests must be recorded or modified in some way before processing.

An ASP. Intercepting filter (intercept filter) mode is an example of an event-driven filter described in this pattern. ASP. NET provides a series of events that an application can hook up during request processing. These events guarantee the status of the request. Each filter is implemented through an HTTP module. An HTTP module is a class that implements the IHttpModule interface and determines when the filter should be called. ASP. NET includes a set of HTTP modules that can be used by applications. For example, SessionStateModule is provided by ASP. To provide the session-State service to the application. You can create your own custom HTTP modules to filter requests or responses based on the needs of your application.

The general process for writing custom HTTP modules is:

Implements the IHttpModule interface.

Process the Init method and register to the event you want.

Handle the event.

If you must clean up, you can also choose to implement the Dispose method.

Registers the module in the Web. config file.

Event

The following table shows the events that can be intercepted by using ASP. All events are listed in the order in which they occur.

The first list shows the events that were generated before the request was processed.

BeginRequest. This event indicates that this is a new request, and each request must produce the event.

AuthenticateRequest. This event indicates that the configured authentication mechanism has verified the request. Attaching to this event enables the filter to ensure that the request is authenticated.

AuthorizeRequest. As with AuthenticateRequest, this event marks a further step in the processing of the request and the request has been authorized.

Resolverequestcache. The output cache module uses this event to simplify the processing of requests that have already been cached.

AcquireRequestState. This event indicates that the status of each request should be obtained.

PreRequestHandlerExecute. This event indicates that the request handler will be executed. This is the last event that you can participate in before calling the HTTP handler for this request.

The next list shows the events that occur after the request is processed. These events are listed in the order in which they occurred:

PostRequestHandlerExecute. This event indicates that the HTTP handler has completed the processing of the request.

ReleaseRequestState. This event indicates that the request state should be stored because the application has completed processing the request.

Updaterequestcache. This event marks the completion of code processing and the ability to add files to the ASP.

EndRequest. This event indicates that all processing of the request has been completed. This is the last event called at the end of the application.

In addition, the following three request pre-processing events can be raised in an indeterminate order:

Presendrequestheaders. This event indicates that the HTTP header will be sent to the client. You can therefore add, remove, or modify header information before you send it.

Presendrequestcontent. This event indicates that the content will be sent to the client. This provides an opportunity to modify the content before it is sent.

Error. This event marks an unhandled exception.

The following is an example of an interception filter built into Microsoft. NET:

Defaultauthenticationmodule. This filter ensures that the authentication object appears in the HttpContext object.

FileAuthorizationModule. This filter verifies that the remote user has the Microsoft Windows NT permissions that are required to access the requested file.

FormsAuthenticationModule. This filter enables an ASP. NET application to use form validation.

PassportAuthenticationModule. This filter provides wrappers that wrap the Passportauthentication service for Passport authentication.

SessionStateModule. This filter provides the session-State service for the application.

UrlAuthorizationModule. This filter provides a URL-based authorization service to allow or deny access to the specified URL.

WindowsAuthenticationModule. This filter enables ASP. NET applications to use the Microsoft windows or Internet Information Services (IIS) authentication mechanism.

Test considerations

If you do not have an ASP. NET runtime, you cannot test the HTTP module. Therefore, a slightly different implementation strategy must be adopted to separate as many functions as possible from the classes that implement the IHttpModule interface. In the preceding example, the code that records the user name does not require the ASP. This feature can be placed in a class named Userlog, which is independent of ASP. The Userlogadapter class that implements the IHttpModule interface can use the Userlog class. In this way, other classes can use the Userlog class, and you can test it without an ASP.

The implementation of the intercepting Filter pattern has the following advantages and disadvantages:

Advantages

1. Use event-driven filters. The ASP. NET runtime provides a number of events, which allows the programmer to hook up to the appropriate location to add functionality. This is an advantage because the programmer can assume the current state of the request based on the event. For example, if the event is authenticaterequest, you can assume that the request has passed the authentication before calling your filter.

2, to achieve flexible configuration. You can add or remove modules by editing the Web. config file. You do not have to change the source code to restart the ASP.

3, reduce the dependence on the order.

Disadvantages:

1, if you do not test the entire ASP. NET runtime, it is difficult or impossible to test classes that implement the IHttpModule interface.

2, the filter should not be related to the order. Because an ASP. NET implementation uses events, it mitigates the problem by using events to indicate that a process has occurred.

Using the Micrisoft.net Design Scenario Chapter III Web presentation mode Web mode cluster details intercepting filter (intercept filter)

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: info-contact@alibabacloud.com 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.