Understand and customize HttpModule

Source: Internet
Author: User

Preface

After understanding and customizing HttpHandler in the previous article, I have further studied HttpModule. This article is a summary.

Main reference: Asp. Net architecture (HttpModule introduction)-Part.3

Directory

1. What is HttpModule?

2. HttpModule in the system.

3. Configure HttpModule.

4. Customize the HttpModule.

5. The Global. asax file and HttpModule.

 

What is HttpModule?

Asp.net events are classified into three levels: application level, page level, and control level. HttpModule subscribes to application-level events of Asp.net in the pipeline model. When an application-level event is triggered, it calls the corresponding processing method in HttpModule. That is to say, HttpModule is the entry to subscribe to Asp.net application-level events and is attached to each event in the lifecycle of the HttpApplication object.

 

HttpModule IN THE SYSTEM

Many internal functions of Asp.net are implemented in the form of HttpModule, such as Windows, Forms, PassPort authentication, and Session mechanism. The following describes the internal HttpModule and its functions.

Name Type Function
OutputCache System. Web. Caching. OutputCacheModule Page-level output Cache
Session System. Web. SessionState. SessionStateModule Session Status Management
WindowsAuthentication System. Web. Security. WindowsAuthenticationModule Use integrated Windows authentication for client authentication
FormsAuthentication System. Web. Security. FormsAuthenticationModule Client authentication using Cookie-based form Authentication
PassportAuthentication System. Web. Security. PassportAuthenticationModule Customer identity verification with MS passport
RoleManager System. Web. Security. RoleManagerModule Manage current user roles
UrlAuthorization System. Web. Security. UrlAuthorizationModule Determine whether a user is authorized to access a URL
FileAuthorization System. Web. Security. FileAuthorizationModule Determine whether a user is authorized to access a resource
AnonymousIdentification System. Web. Security. AnonymousIdentificationModule Manage anonymous access in Asp. Net Applications
Profile System. Web. Profile. ProfileModule Manage the creation of user archive files and related events
ErrorHandlerModule System. Web. Mobile. ErrorHandlerModule Capture exceptions, format error message characters, and pass them to the client program

 

Configure HttpModule

The custom HttpModule is similar to the custom HttpHandler and must be configured in the web. config file. The format is as follows:

1 <HttpModules>
2 <add name="MM" type="MyModule,MMAssembly"/>
3 </HttpModules>

1. type: similar to HttpHandler, it consists of two parts: the first part is the complete class name (including the namespace name), and the second part is the name of the Assembly (excluding. dll ).

2. name: The name of HttpModule, which may be unrelated to the class name. Use the Modules attribute of the HttpApplication object to obtain the HttpModuleCollection, and then use the name to obtain the corresponding HttpModule object. in asax, use the method name ModuleName_EventName to subscribe to events in HttpModule. Here is the specific event name of MM _. For details, see the following example.

3. because every request that enters the working process is processed by the configured HttpModule (because the HttpModule subscribes to application-level events ), therefore, the configuration file does not have the path and verb attributes (whether *. aspx or *. ashx. Requests in get or post format are processed ).

Note: The configuration of HttpModule does not need to be configured on IIS like HttpHandler.

 

Custom HttpModule

Each HttpModule inherits the System. Web. IHttpModule interface and implements the Init (HttpApplication context) and Dispose () Methods of the interface. As follows:

 1 public class MyModule:IHttpModule
2 {
3
4 public void Init(HttpApplication context)
5 {
6 context.BeginRequest += new EventHandler(context_BeginRequest);
7 }
8
9 void context_BeginRequest(object sender, EventArgs e)
10 {
11 HttpContext.Current.Response.Write("BeginRequest");
12 }
13
14 public void Dispose()
15 {
16 }
17 }

Init (): This method accepts an HttpApplication object. HttpApplication represents the current application. In this method, we need to subscribe to the events exposed to the client by the HttpApplication object. It can be seen that this method is only used to subscribe to events, and the actual event processing program requires another writing method.

Dispose (): Release resources before garbage collection.

The entire process is well understood:

  1. When the first resource of the site is accessed, Asp. net will create an HttpApplication class instance, which represents the site application, at the same time will create all in the Web. the Module instance that has been registered in Config.
  2. The Module Init () method is called when a Module instance is created.
  3. Register the events exposed by the HttpApplication that you want to respond to in the Init () method. (Only simple registration of methods is required. The actual method needs to be written separately ).
  4. HttpApplication triggers various events in its application cycle.
  5. When an event is triggered, call the method that the Module has registered in its Init () method.

For more information about delegation, see delegation and events.

 

G Lobal. asax file and HttpModule

In asp.net, Glabal not only registers applications and Session events, but also registers events exposed by the Http Module. It can not only register system Module events, you can also register the events exposed by our own Module. Before proceeding to the specific introduction, pay attention to the following two points:

  1. Each time an Http request is processed, the application event is triggered again, except Application_Start and Application_End. This event is triggered only when the first resource file is accessed.
  2. The Http Module cannot register and respond to Session events. For Session_Start and Session_End, they can only be handled through Glabal. asax.

Continue with the above example:

MyModule. cs File

1 public class MyModule: IHttpModule
2 {
3 public event EventHandler ExposedEvent; // HttpModule event for Global. asax to subscribe
4
5 public void Init (HttpApplication context)
6 {
7 context. BeginRequest + = new EventHandler (context_BeginRequest); // subscribe to HttpApplication events
8}
9
10 void context_BeginRequest (object sender, EventArgs e)
11 {
12 HttpContext. Current. Response. Write ("BeginRequest ");
13 OnExposedEvent (new EventArgs (); // triggers the HTTP module Custom Event
14}
15
16 protected void OnExposedEvent (EventArgs e)
17 {
18 if (ExposedEvent! = Null)
19 {
20 ExposedEvent (this, e );
21}
22}
23
24 public void Dispose ()
25 {
26}
27}

Global. asax File

1 void MyModule_ExposedEvent(object sender, EventArgs e)
2 {
3 Response.Write("xixi");
4 }

The above MyModule_ExposedEvent method automatically subscribes to the ExposedEvent event in MyModule. The specific implementation mechanism remains to be studied!

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.