[C #. Net] HTTP module introduction -)

Source: Internet
Author: User
Introduction to HTTP Module

In the two articles, HTTP request processing process and HTTP handler introduction, we first understand the processing process of HTTP requests on the server side, then we know that the HTTP request will eventually be processed by the class implementing the ihttphandler interface (remember that the page class implements ihttphandler ). From the last figure in the HTTP request processing process, we can see that before the HTTP request is processed by ihttphandler, it needs to use a series of HTTP modules. After the request is processed, it needs to pass a series of HTTP modules again. How are these HTTP modules made up? What is used? This article describes the HTTP module.

HTTP module Overview

We will not consider implementing the HTTP module on our own. In. net, the HTTP module is an assembly that implements the ihttpmodule interface. The ihttpmodule interface does not have any upper-case close-up. It can be seen from its name that it is just an ordinary interface. In fact, we are concerned about the classes that implement these interfaces. If we write code to implement this interface, what is the purpose. In general, we can set ASP.. Net events are divided into three levels: application-level events, page-level events, and control-level events, the event trigger is closely related to the application cycle, page cycle, and control cycle.The role of the HTTP module is closely related to application events.

We use the HTTP module to register the method expected to respond to application events in the HTTP request pipeline (pipeline). When the corresponding event is triggered (such as the beginrequest event, when an application receives an HTTP request and is about to process it), it calls the method registered by the HTTP module. The actual work is executed in these methods .. Net itself already has many HTTP modules, including form verification module (formsauthenticationmodule), session Status Module (sessionstatemodule), and output cache module (outputcachemodule.

Register an HTTP Module

Before registering our own HTTP module, let's take a look at the existing HTTP module in ASP. NET. Similar to HTTP handler, we need to open the Web. config file under the c: \ windows \ microsoft. Net \ framework \ v2.0.50727 \ config directory on the machine. Find the

<Httpmodules>
<Add name = "outputcache" type = "system. Web. caching. outputcachemodule"/>
<Add name = "session" type = "system. Web. sessionstate. sessionstatemodule"/>
<Add name = "windowsauthentication" type = "system. Web. Security. windowsauthenticationmodule"/>
<Add name = "formsauthentication" type = "system. Web. Security. formsauthenticationmodule"/>
<Add name = "passportauthentication" type = "system. Web. Security. passportauthenticationmodule"/>
<Add name = "rolemanager" type = "system. Web. Security. rolemanagermodule"/>
<Add name = "urlauthorization" type = "system. Web. Security. urlauthorizationmodule"/>
...
</Httpmodules>

First, we can see from the node that the type attribute is similar to the type attribute of the HTTP handler node mentioned in the previous section and represents the corresponding assembly. However, unlike HTTP handler, the module only provides a name attribute and does not specify a specific file handler (or use wildcard * to represent a specific type) such as path. This is related to the features of the module. We know that the module responds to events triggered during the application cycle, and all requests submitted to aspnet_isapi.dll are the same, even if the request only gets an image like a http://www.tracefact.net/images/logo.gif (after setting ISAPI, the default aspnet_isapi.dll does not take over the image file ).

Similar to HTTP handler, in our own HTTP module, assume that the class name is moduledemo, which is located in the mynamespace namespace and the Assembly name is mydll. the DLL is copied to the bin directory and stored in the web. config file system. create an httpmodules node under a web node:

<System. Web>
<Httpmodules>
<Add name = "custommodulename" type = "mynamespace. moduledemo, mydll"/>
</Httpmodules>
</System. Web>

The Type attribute is divided into two parts: namespace and class name, that is, type name; followed by the Set Name. If we create the code in the app_code directory, you do not need to specify the Set Name.

The name attribute is named by ourselves, not necessarily the same as the class name. Here I name it "mmmodulename ". We can get the httpmodulecollection through the modules attribute of the application (httpapplication), and then get the httpmodule object through the name attribute.

Through the name attribute, we can also. in the asax file, compile the event processing program exposed by the custom httpmodule. The format is void modulename_eventname (Object sender, eventargs E ). We will give a more detailed introduction later.

HTTP modules built in ASP. NET

The following table lists the HTTP modules built in ASP. NET in Web. config under c: \ windows \ microsoft. Net \ framework \ v2.0.50727 \ config and their main 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

We will program it later.

Ihttpmodule Interface

After reading so much theoretical knowledge, this section will start to write some programs to implement your own HTTP module. First, let's take a look at the ihttpmodule interface, which includes the following two methods:

Public void Init (httpapplication context );
Public void dispose ();

Init (): This method accepts an httpapplication object. httpapplication represents the current application, and we need to register the event where the httpapplication object is exposed to the client in this method. It can be seen that this method is only used to register events, and the actual event processing program requires us to write another method.

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.

Note: If you do not know about event registration and other related content, see the delegate and event article in C.

Dispose (): It can be cleaned up before garbage collection.

To sum up, an ihttpmodule template is generally like this:

Public class moduledemo: ihttpmodule
{
Public void Init (httpapplication context ){
// Register the httpapplication beginrequest event
// It can also be an event exposed by any other httpapplication.
Context. beginrequest + = new eventhandler (context_beginrequest );
}

Void context_beginrequest (Object sender, eventargs e ){
Httpapplication application = (httpapplication) sender;
Httpcontext context = application. context;
// Do some practical work. The httpcontext object is obtained, and the rest can be used freely.
}

Public void dispose (){
}
}

Write text to the HTTP request output stream through the HTTP Module

In this example, we only use the beginrequest event and endrequest event to describe how to use the HTTP module. This example shows how to use the HTTP module.

First, create a new site and add the class file: moduledemo. CS: To the app_code directory:

Public class moduledemo: ihttpmodule
{
// The init method is only used to register the method for the expected event
Public void Init (httpapplication context ){
Context. beginrequest + = new eventhandler (context_beginrequest );
Context. endrequest + = new eventhandler (context_endrequest );
}

// The actual code used to process the beginrequest event
Void context_beginrequest (Object sender, eventargs e ){
Httpapplication application = (httpapplication) sender;
Httpcontext context = application. context;
Context. response. Write ("<H1 style = 'color :# 00f'> processing from httpmodule, request arrival }

// The actual code used to process the endrequest event
Void context_endrequest (Object sender, eventargs e ){
Httpapplication application = (httpapplication) sender;
Httpcontext context = application. context;
Context. response. Write ("<HR> <H1 style = 'color: # f00'> processing from httpmodule, end of request }

Public void dispose (){
}
}

The above code is very simple. It registers the beginrequest event and endrequest event of the httpapplication instance. The event processing method is only used at the beginning and end of the HTTP request, write different content to the input stream of the HTTP request.

Next, write the following content in the system. Web node of Web. config:

<System. Web>
<Httpmodules>
<Add name = "mymodule" type = "moduledemo"/>
</Httpmodules>
</System. Web>

Then, open the default. aspx file automatically created when the site is created, and type a few words in it. To differentiate it, I entered the text on the. ASPX page. Then, open it in the browser and you will see something like this:

Then we create a new default2.aspx, Which is browsed in the browser. We can see that the two pages have the same effect. This indicates that the HTTP module works for different two files. It can be seen that it is indeed at the application level rather than the page level.

Now, we open an image file on the site and find that it shows a Red Cross. Why? Because the HTTP module is for an HTTP request, rather than a certain type of files, when requesting an image, the HTTP module we wrote will still work and insert the text into the binary image, if the file format is damaged, only the Red Cross is displayed.

Note:Don't be surprised if you find that your images are normally displayed. The thing is this: Let's look back at the first section we discussed. For image files, they are directly processed by IIS and will not be handed over to aspnet_isapi.dll, therefore, the module cannot capture requests for image files. The solution is to set it in IIS.
Note that if you use the local server that comes with vs2005, you do not need to set IIS. All images or any file types will be processed by aspnet_isapi.dll.

Traverse the HTTP module set

Now, we can traverse the httpmodulecollection set to view the names of all the HTTP modules registered to the application.

Create a file registeredmodules. aspx and add the following method to the Code POST file:

Private string showmodules (){
Httpapplication APP = context. applicationinstance; // obtain the httpapplication environment of the current context
Httpmodulecollection modulecollection = app. modules; // gets all module Sets

// Obtain the names of all modules
String [] modulenames = modulecollection. allkeys;

System. Text. stringbuilder Results = new system. Text. stringbuilder (); // traverses the result set

Foreach (string name in modulenames ){
// Obtain the module name
Results. append ("<B style = 'color: #800800 '> name:" + name + "</B> <br/> ");
// Obtain the module type
Results. append ("type:" + modulecollection [name]. tostring () + "<br/> ");
}

Return results. tostring ();
}

Then output the following in the page_load method:

Protected void page_load (Object sender, eventargs E)
{
Response. Write (showmodules ());
}

We can see the following picture:

Compared with the table listed above, we can see that it is almost identical (with an additional defaultauthentication ). In addition, in the last and last lines of attention, isn't the module defined by ourselves? The name is mymodule and the type is moduledemo.

Global. asax file and HTTP Module

As early as the ASP era, everyone knows this file. It is mainly used to place responses to application events or session events. You are familiar with application_start, application_end, session_start, and session_end.

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.

Now let's modify the previous moduledemo sample program and add an event to it as follows (to simplify the program, I simplified it ):

Public class moduledemo: ihttpmodule {

// Declare an event
Public event eventhandler exposedevent;

// The init method is only used to register the method for the expected event
Public void Init (httpapplication context ){
Context. beginrequest + = new eventhandler (context_beginrequest );
}

// The actual code used to process the beginrequest event
Void context_beginrequest (Object sender, eventargs e ){
Httpapplication application = (httpapplication) sender;
Httpcontext context = application. context;
Context. response. Write ("<H3 style = 'color :# 00f'> processing from httpmodule, request arrival
Onexposedevent (New eventargs (); // CALL THE METHOD
}

Protected override void onexposedevent (eventargs e ){
If (exposedevent! = NULL) // If registered in global
Exposedevent (this, e); // call the registered Method
}

Public void dispose (){
}
}

Next, create a global. asax file in the site and add the following code to it. Note that the format is void module name_event name (Object sender, eventargs E ).

Void mymodule_exposedevent (Object sender, eventargs E)
{
Response. Write ("<H3 style = 'color: #800800 '> text from global. asax </H2> ");
}

Now, we can see this on the previous page. We have successfully linked the glabal. asax file to the event exposedevent exposed by our custom HTTP module:

Summary

This article briefly introduces what is an HTTP module. We first understood the role of the HTTP module, and then checked ASP. net built-in module, then we introduced the ihttpmodule interface, and implemented this interface through a simple example, finally we discussed HTTP module and global. asax file contact.

This article only briefly introduces the ihttpmodule and adds more practical applications to subsequent articles.

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.