HttpModule for custom Http processing and application in ASP. Net, asp. nethttpmodule

Source: Internet
Author: User

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
  1. Example 1:
  2. Using System;
  3. Using System. Web;
  4. Namespace MyModule
  5. {
  6. Public class MyModule: IHttpModule
  7. {
  8. Public void Init (HttpApplication application)
  9. {
  10. Application. BeginRequest + = (new
  11. EventHandler (this. Application_BeginRequest ));
  12. Application. EndRequest + = (new
  13. EventHandler (this. Application_EndRequest ));
  14. }
  15. Private void Application_BeginRequest (Object source, EventArgs e)
  16. {
  17. HttpApplication Application = (HttpApplication) source;
  18. HttpResponse Response = Application. Context. Response;
  19. Response. Write ("
  20. }
  21. Private void Application_EndRequest (Object source, EventArgs e)
  22. {
  23. HttpApplication application = (HttpApplication) source;
  24. HttpResponse Response = Application. Context. Response;
  25. Response. Write ("
  26. }
  27. Public void Dispose ()
  28. {
  29. }
  30. }
  31. }

 

 

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
  1. <Configuration>
  2. <System. web>
  3. <HttpModules>
  4. <Add name = "MyModule" type = "MyModule, MyModule"/>
  5. </HttpModules>
  6. </System. web>
  7. </Configuration>


Now let's take a look at the effect. Compile An Aspx page test. aspx with the following content:

[C-sharp]View plaincopy
  1. <%
  2. Response. Write ("
  3. %>


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
  1. Public class RightChecker
  2. {
  3. Public static bool HasRight (User user, Module module)
  4. {
  5. // Perform permission verification,
  6. }
  7. }



Then, we use HttpModule to write a filter:

[C-sharp]View plaincopy
  1. Using System;
  2. Using System. Web;
  3. Namespace MyModule
  4. {
  5. Public class MyModule: IHttpModule
  6. {
  7. Public void Init (HttpApplication application)
  8. {
  9. Application. AcquireRequestState + = (new
  10. EventHandler (this. Application_AcquireRequestState ));
  11. }
  12. Private void Application_AcquireRequestState (Object source,
  13. EventArgs e)
  14. {
  15. HttpApplication Application = (HttpApplication) source;
  16. User user = Application. Context. Sesseion ["User"] // obtain the User
  17. String url = Application. Context. Request. Path;
  18. // Obtain the page accessed by the customer
  19. Module module = // obtain the Module based on the url
  20. If (! RightChecker. HasRight (user, module ))
  21. Application. Context. Server. Transfer ("ErrorPage. aspx ");
  22. // If you do not have the permission, go to the error handling page
  23. }
  24. Public void Dispose ()
  25. {
  26. }
  27. }
  28. }

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.

Related Article

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.