Httphandlers and httpmodules provide two ways to process requests and responses by extending the original page framework. The main purpose of httphanders is to process requests to a specific file or a file path in a URL, httpmodule is mainly used to process a request and a response in the initial stage.
Httphandlers refers to the class that implements the ihttphandler interface. They get references to the current httpcontext object in the processrequest () method, and can execute code based on the attributes of the httpcontext object. A typical example is that httphandler analyzes the data from the request property (object) and sends back something through the Response Property (object. Httphandler simultaneously implements an isreusable attribute, which tells Asp.net whether the same instance of the class can be used to process concurrent (subsequent) requests.
Step 1: first create a class library project:
Using system;
Using system. Web;
Public class handler: ihttphandler
{
Public void processrequest (httpcontext context)
{
Context. response. Write ("AAA ");
}
Public bool isreusable
{
Get
{
Return false;
}
}
}
Step 2: reference this DLL in a web project
Step 3: Configure in Web. config. The type parameter is namespace name, class name, and set name.
<Httphandlers>
<Add verb = "*" Path = "*. aspx" type = "handler, classlibrary1"/>
</Httphandlers>
Now, no matter which aspx file you access, AAA is returned!
Httpmodules adds an event processor to an application event so that the code can interact with the application. All these classes must implement the ihttpmodule interface. The init () method provides us with reference to an application. In this method, we can bind the event processor to the application event. The event processor interacts with the application by implementing the basic event processor markup. Httpmodule also implements a dispose () method, which is used to execute necessary cleanup at the end of the application.
Step 1: first create a class library project:
Namespace classlibrary1
{
Class class2: ihttpmodule
{
Public void dispose ()
{
// Throw new exception ("the method or operation is not implemented .");
}
Public void Init (httpapplication context)
{
Context. Context. cache ["A"] = "";
}
}
}
Step 2: add this reference to the Web Application
Step 3: configure the name in Web. config. The Type format is namespace name. Class Name.
<Httpmodules>
<Add name = "A" type = "classlibrary1.class2"/>
</Httpmodules>
Step 4: Verify in the Web Application
If (Cache ["A"]! = NULL)
{
Response. Write (Cache ["A"]. tostring ());
}
Else
{
Response. Write ("no ");
}
As you can see, a is printed
In fact, httpmodule responds before httphandler, so it can affect the latter.