HttpModule for custom Http processing and application in ASP. Net, asp. nethttpmodule
HttpHandler implements functions similar to ISAPI Extention. It processes Request information and sends Response ). The HttpHandler function is implemented through the IHttpHandler interface. HttpModule implements functions similar to ISAPI Filter.
HttpModule implementation
HttpModules implements functions similar to ISAPI Filter. Generally, the following steps are required during development:
1. Write a class to implement the IhttpModule Interface
2. Implement the Init method and register the required Method
3. Registration Method
4. Implement the Dispose method. If you need to manually clear the class, you can add the implementation of the Dispose method, but this is not necessary. Generally, you can not add any code for the Dispose method.
5. register the class you have written in the Web. config file.
The following is an example of HttpModules. In this example, only the BeginRequest and EndRequest events of HttpApplication are registered, and relevant information is printed out through the implementation of these events.
[C-sharp]View plaincopy
- Example 1:
- Using System;
- Using System. Web;
- Namespace MyModule
- {
- Public class MyModule: IHttpModule
- {
- Public void Init (HttpApplication application)
- {
- Application. BeginRequest + = (new
- EventHandler (this. Application_BeginRequest ));
- Application. EndRequest + = (new
- EventHandler (this. Application_EndRequest ));
- }
- Private void Application_BeginRequest (Object source, EventArgs e)
- {
- HttpApplication Application = (HttpApplication) source;
- HttpResponse Response = Application. Context. Response;
- Response. Write ("
- }
- Private void Application_EndRequest (Object source, EventArgs e)
- {
- HttpApplication application = (HttpApplication) source;
- HttpResponse Response = Application. Context. Response;
- Response. Write ("
- }
- Public void Dispose ()
- {
- }
- }
- }
The following namespace is referenced at the beginning of the program:
using System;using System.Web; |
Because classes such as HttpApplication, HttpContext, and HttpResponse are defined in System. Web, System. Web namespaces must be referenced.
The MyModule class implements the IhttpModule interface. The Init method specifies the method for implementing the BeginRequest and EndRequest events. In the two methods, some information is simply printed separately.
Next, register this class in the Web. config file and you can use this HttpModule. The registration method is as follows:
[C-sharp]View plaincopy
- <Configuration>
- <System. web>
- <HttpModules>
- <Add name = "MyModule" type = "MyModule, MyModule"/>
- </HttpModules>
- </System. web>
- </Configuration>
Now let's take a look at the effect. Compile An Aspx page test. aspx with the following content:
[C-sharp]View plaincopy
- <%
- Response. Write ("
- %>
After running:
In-depth research on HttpModule
HttpModule processes a series of events of the HttpApplication object to influence the HTTP processing pipeline. These events are registered in the Init method of HttpModule, including:
BeginRequestAuthenticateRequestAuthorizeRequestResolveRequestCacheAcquireRequestStatePreRequestHandlerExecutePostRequestHandlerExecuteReleaseRequestStateUpdateRequestCacheEndRequest |
Some of the events correspond to events in Global. asax. The corresponding relationship is as follows:
HttpModule |
Global. asax |
BeginRequest |
Application_BeginRequest |
AuthenticateRequest |
Application_AuthenticateRequest |
EndRequest |
Application_EndRequest |
In example 1, The BeginRequest and EndRequest events are processed. The processing methods for other events are similar.
According to HttpHandler, some of these events occur before HttpHandler, and some occur after HttpHandler completes processing. It is very important to understand the sequence of events, because the objects on the server have different performance in different time periods. One example is the use of Session. Not all events can process sessions, but only a limited number of events. For detailed procedures, refer to the following HTTP Request processing lifecycle diagram.
Use HttpModule to implement the Permission System
When developing an application system, permission control of the application system is very important. In ASP, permission control is troublesome, because we must add permission control code to each ASP page that requires permission control to control access to the page. In addition to writing a large number of repeated code, the permission control module is closely coupled with the business processing module to modify the permission control module, it often brings about a lot of modifications and even a lot of bugs.
Therefore, we need to decouple the permission control and business processing modules so that the two parts can be developed and modified independently without affecting each other or minimizing the impact. In Jsp programs, this goal can be achieved by introducing a front-end controller to implement permission filtering (for details about the front-end controller mode, see the J2EE Core mode book). In ASP. Net, we can use HttpModule to achieve the same effect. The following describes the implementation process.
First, we will build a permission processing system that can detect whether a user has access to a module's functions (the specific structure, I think, readers should have access to this part of programming, so I will not go into details). The definitions of the permission verification class exposed to client calls are as follows:
[C-sharp]View plaincopy
- Public class RightChecker
- {
- Public static bool HasRight (User user, Module module)
- {
- // Perform permission verification,
- }
- }
Then, we use HttpModule to write a filter:
[C-sharp]View plaincopy
- Using System;
- Using System. Web;
- Namespace MyModule
- {
- Public class MyModule: IHttpModule
- {
- Public void Init (HttpApplication application)
- {
- Application. AcquireRequestState + = (new
- EventHandler (this. Application_AcquireRequestState ));
- }
- Private void Application_AcquireRequestState (Object source,
- EventArgs e)
- {
- HttpApplication Application = (HttpApplication) source;
- User user = Application. Context. Sesseion ["User"] // obtain the User
- String url = Application. Context. Request. Path;
- // Obtain the page accessed by the customer
- Module module = // obtain the Module based on the url
- If (! RightChecker. HasRight (user, module ))
- Application. Context. Server. Transfer ("ErrorPage. aspx ");
- // If you do not have the permission, go to the error handling page
- }
- Public void Dispose ()
- {
- }
- }
- }
After registering this class in Web. Config according to the method described above, our application system will have the permission management function. How is it better than the original method?
Conclusion
In. in. Net, Microsoft has greatly simplified the programming of server extension that previously had relatively high difficulty, which has indeed brought great convenience to our development, it is worth our in-depth research on this technology.
Differences between httphandler and httpmodule
ASP. when the Http Request is processed by Net, the requests are processed by each HttpModule in the Pipeline (Pipeline) mode and then to HttpHandler. After the HttpHandler completes processing, the requests are still processed by each HttpModule in the Pipeline, finally, the HTML is sent to the client browser. HttpModule processes pages before and after page processing, so it does not affect real page requests. It is usually used to add some information (such as copyright notice) to the header or tail of each page. The differences between IHttpModule and IHttpHandler are sorted out.
1. sequence. IHttpModule first, and then IHttpHandler. Note: The Module depends on the event you have responded to. Some events run before Handler, and some run after Handler.
2. processing the request:
IHttpModule is a type of generic size. It is called no matter what file the client requests. For example, aspx, rar, and html requests.
IHttpHandler belongs to the picky eaters type. Only the file types registered by ASP.net (such as aspx and asmx) can call it.
3. IHttpHandler generates a response based on your request. The IHttpModule pre-processes the request, such as verification, modification, and filtering. It can also process the response. The HttpModule inherits the System. web. IHttpModule interface to implement your own HttpModule class. Two methods must be implemented: Init and Dispose. In Init, you can add events to be intercepted. Dispose is used to release resources. If you have created your own resource objects in Init, release them in Dispose. Use the custom HttpModule, httpHandler completely intercepts Http requests for purposes such as global identity/permission verification, custom Website access/operation log recording, and site monitoring and tracing for management/debugging.
First, inherit the System. Web. IHttpHandler interface to implement your own HttpHandler class. The ProcessRequest method and IsReusable attribute of the interface must be implemented. The ProcessRequest method processes each Http Request and sends the HTML of the processing result to the output cache. The IsReusable attribute is called by the. Net Framework to determine whether the HttpHandler instance can be reused for other requests of the same type.
If you need to read or write the Session value in your HttpHandler class, you need to inherit an IRequiresSessionState interface. This interface does not have any method, but is only a tag interface. After inheriting this interface, you can access the Session in your HttpHandler and write the value in the Session.
Why does AspNet jump to the page in HttpModule?
If your httpmodule is set to jump to a page if you do not log on to the page, this judgment will be executed when the page is postback, so you should not say this problem.
So I feel that the jump to your httpmodule may not be written to the correct path. It is estimated that your login page is not in the same directory as this page. Therefore, write the jump in httpmodule as an absolute path.