Application of HTTP requests in Asp.net

Source: Internet
Author: User
When a * .aspxfile is requested, the request will be intercepted by the inetinfo.exe process. After determining the file suffix (aspx), it will forward the request to aspnet_isapi.dll, aspnet_isapi.dll sends the request to aspnet_wp.exein the HTTP pipeline. The request is processed through httpruntime in the aspnet_wp.exe process. After the request is processed, the result is returned to the client.
Inetinfo.exe process: the process of WWW Service. Both IIS service and aspnet_isapi.dll are stored in this process.
Aspnet_isapi.dll: A Win32 component used to process the. aspx file. The iisserver can only identify the .html file. When the IIS server finds that the requested file is a. aspx file, the IIS server submits it to aspnet_isapi.dll for processing.
Aspnet_wp.exe process: an ASP. NET Framework process that provides a managed environment for. Net Running. the. net clr (runtime in public language) is stored in this process.

ASP. NET Framework processes an HTTP request:
Httprequest --> inetinfo.exe --> response --> aspnet_wp.exe --> httpruntime --> httpapplication factory --> httpapplication --> httpmodule --> httphandler factory --> httphandler. processrequest ()

ASP. the net request processing process is based on the pipeline model, which consists of multiple httpmodules and httphandler, Asp.. Net passes the HTTP request to each httpmodule in the pipeline in sequence, and is finally processed by httphandler. After the processing is completed, it passes through the HTTP module in the pipeline again and returns the result to the client. We can intervene in the request processing process in each httpmodule.

Note: During HTTP request processing, only one httphandler can be called, but multiple httpmodules can be called.
When the request arrives at httpmodule, the system has not actually processed the request, but we can add some other information before the request is passed to the processing center (httphandler, or intercept the request and do some additional work, or terminate the request. After httphandler finishes processing the request, we can re-process the request processing result in the corresponding httpmodule and return it to the client.

Httpmodule
The HTTP module is a class that implements the system. Web. ihttpmodule interface.
Ihttpmodule interface declaration:
Public interface ihttpmodule
{
Void Init (httpapplication context );
Void dispose ();
}
Init method: automatically called during system initialization. This method allows the HTTP module to register its own event processing with the event in the httpapplication object.Program.
Dispose method: This method gives the HTTP module the opportunity to clean up objects before they are collected by garbage collection. This method is generally not requiredCode.

The HTTP module registers the following events with the system. Web. httpapplication object:
Acquirerequeststate this event is triggered when ASP. NET is ready to receive the current HTTP request dialog state.
Authenticaterequest this event is triggered when ASP. NET is running to authenticate the user identity.
Authorizerequest this event is triggered when ASP. NET is ready to authorize users to access resources.
Beginrequest this event is triggered when ASP. NET receives a new HTTP request.
Disposed this event is triggered when ASP. NET completes the HTTP request processing process.
This event is triggered before the endrequest sends the response content to the client.
An error occurs when an unhandled exception occurs during HTTP request processing.
Postrequesthandlerexecute triggers this event when the HTTP processing program ends.
Prerequesthandlerexecute raises this event before ASP. NET starts executing the HTTP request processing program. After this event, ASP. NET forwards the request to an appropriate HTTP handler.
Presendrequestcontent triggers this event before ASP. NET sends the response content to the client. This event allows us to change the response content before the content arrives at the client. We can use this event to add content for all pages to the page output. For example, general menu, header information, or foot information.
Presendrequestheaders triggers this event before ASP. NET sends the HTTP response header information to the client. Before the header information arrives at the client, this event allows us to change its content. We can use this event to add cookies and custom data to the header information.
Releaserequeststate this event is triggered when ASP. NET finishes executing the searched request processing program.
Resolverequestcache triggers this event to determine whether the request can end with the content returned from the output buffer. This depends on how to set the web application output buffer.
Updaterequestcache this event is triggered when ASP. NET processes the current HTTP request and the output content is ready to be added to the output buffer. This depends on how the web application's output buffer is set.

The above events may seem dizzy, but it doesn't matter. Let's take a look at them step by step.
Httpmodule Lifecycle

The event trigger sequence is as follows:

The event between beginrequest and prerequesthandlerexecute is triggered before the server executes httphandler processing.
Events between postrequesthandlerexecute and presendrequestcontent are triggered after the server executes handler processing.

Next, let's take a look at how to use httpmodule to implement our daily applications:
Httpmodule inserts itself into the ASP. NET Request Processing pipeline by registering in some events. When these events occur, ASP. NET calls the corresponding HTTP module so that the module can process requests.
1. Add some remarks or descriptive text to each page dynamically:
In some websites, an advertisement is displayed on each page or the copyright information of the website is added in the form of a comment () on each page. If you want to write such JS Code on each page, writing and maintaining such JS Code for a large website is a tedious task.
With httpmodule, we can easily solve this problem. Httpmodule is the only way for the client to send a request to the client to receive the server response. After the server completes processing the request and sends the response text to the client, we can add the comment text to the page text. In this way, each page request will be appended with this text comment.
In which event should this code be implemented? Any event between postrequesthandlerexecute and presendrequestcontent can be used, but I prefer to write code in the endrequest event.
Step 1: Create a class library classlibrary831.
Step 2: compile a class to implement the ihttpmodule Interface
Class testmodule: ihttpmodule
{
Public void dispose ()
{
}
Public void Init (httpapplication context)
{
}
}
Step 3: register the endrequest event in the init event and implement the event processing method.
Class testmodule: ihttpmodule
{
Public void dispose (){}
Public void Init (httpapplication context)
{
Context. endrequest + = new eventhandler (context_endrequest );
}
Void context_endrequest (Object sender, eventargs E)
{
Httpapplication HA = (httpapplication) sender;
Ha. response. Write ("");
}
}
Step 4: register the httpmodule module in Web. conofig

Name: Module name, which is generally a class name
Type: it consists of two parts: the first half is the full name composed of the namespace and class name, and the second half is the Assembly name. If the class is directly placed in the app_code folder, the program name is app_code.
In this way, after you add a reference to the class library on the web site and run each page, you will find that "" is added to the source file. You can also add js code in the same method.
2. Identity check
When you log on successfully, you generally need to store the user name in the session and check whether there is a user name in the session in the page_load event of each other page, if it does not exist, it indicates that the user has not logged on and will not allow the user to access the content.
In a relatively large program, this method is too clumsy, because you have to add the detection session code in almost every page, making it difficult to develop and maintain. Next, let's take a look at how to use httpmodule to reduce our workload.
Because we need to use the session content here, we can only write code in the acquirerequeststate and prerequesthandlerexecute events, because only these two events in httpmodule can access the session. Here, we select the prerequesthandlerexecute event to write code.
Step 1: Create a class library classlibrary831.
Step 2: compile a class to implement the ihttpmodule Interface
Class testmodule: ihttpmodule
{
Public void dispose ()
{
}
Public void Init (httpapplication context)
{
}
}
Step 3: register the prerequesthandlerexecute event in the init event and implement the event processing method.
Class authenticmodule: ihttpmodule
{
Public void dispose (){}
Public void Init (httpapplication context)
{
Context. prerequesthandlerexecute + = new eventhandler (context_prerequesthandlerexecute );
}
Void context_prerequesthandlerexecute (Object sender, eventargs E)
{
Httpapplication HA = (httpapplication) sender;
String Path = ha. Context. Request. url. tostring ();
Int n = path. tolower (). indexof ("login. aspx ");
If (n =-1) // whether it is a logon page. If it is not a logon page, enter {}
{
If (Ha. Context. session ["user"] = NULL) // whether the session has a user name. If it is null, go to the logon page.
{
Ha. Context. response. Redirect ("login. aspx? Source = "+ path );
}
}
}
}
Step 4: Add the following code to the "Log on" button on the login. ASPX page
Protected void button#click (Object sender, eventargs E)
{
If (true) // determine whether the user name and password are correct
{
If (request. querystring ["Source"]! = NULL)
{
String S = request. querystring ["Source"]. tolower (). tostring (); // retrieve the page from which it is converted
Session ["user"] = txtuid. text;
Response. Redirect (s); // go to the desired page
}
Else
{
Response. Redirect ("Main. aspx"); // default switch to main. aspx
}
}
}
Step 5: register the httpmodule module in Web. conofig

3. multi-module operations
If multiple httpmodules are defined, the order in which custom httpmodules are introduced in the web. config file determines the order in which multiple custom httpmodules take over an HTTP request.

Httphandler
Httphandler is the processing center of HTTP requests. It truly compiles and executes the server pages of client requests, and attaches the processed information to the HTTP request information stream and returns it to httpmodule again.
Httphandler is different from httpmodule. Once you define your own httphandler class, its relationship to the system's httphandler will be "overwritten.
Ihttphandler interface declaration
Public interface ihttphandler
{
Bool isreusable {Get ;}
Public void processrequest (httpcontext context); // request processing function
}

Example: Write the image on the hard disk as a stream on the page
Class testhandler: ihttphandler
{
Public void processrequest (httpcontext context)
{
Filestream FS = new filestream (context. server. mappath ("worm.jpg"), filemode. Open );
Byte [] B = new byte [fs. Length];
FS. Read (B, 0, (INT) fs. Length );
FS. Close ();
Context. response. outputstream. Write (B, 0, B. Length );
}
Public bool isreusable
{
Get
{
Return true;
}
}
}
Web. config configuration file

Verb attribute: Specifies the HTTP action supported by the handler. *-All HTTP actions are supported. "Get"-Get operations are supported. "Post"-post operations are supported. "Get and post"-two operations are supported.
Path attribute: Specifies the path and file name of the handler to be called (which can contain wildcards ). "*", "*. Aspx", "showimage. aspx", "test1.aspx, test2.aspx"
Type attribute: specify the actual type of the handler or handler factory by combining the namespace, class name, and assembly name. When ASP. NET is running, search for the DLL in the bin directory and then GAC.
The result of running this program is that any page on the website displays the worm.jpg image. How can I have only one page (default21.aspx) execute the processrequest method in httphandler? The simplest way is to set the path configuration information to default21.aspx in the web. config file.
Based on this example, you can consider how to compile the "Verification Code.

Ihttphandler Factory
Ihttphandlerfactory is used to manage ihttphandler. For the role of the factory, see http://hi.baidu.com/grayworm/blog/item/4a832160f8c9de46eaf8f8c1.html"
Ihttphandlerfactory interface declaration:
Public interface ihttphandlerfactory
{
Ihttphandler gethandler (httpcontext context, string requesttype, string URL, string pathtranslated );
Void releasehandler (ihttphandler handler );
}
Gethandler returns an instance of the class implementing the ihttphandler interface. releasehandler allows the factory to reuse existing handler instances.
Example: two calls to different httphandlerfactory are implemented using ihttphandlerfactory.
There are two httphandler: The httphandler that displays the image on the page and the handler that generates the verification code
// Handler that displays the image on the page
Class testhandler: ihttphandler
{
Public void processrequest (httpcontext context)
{
Filestream FS = new filestream (context. server. mappath ("worm.jpg"), filemode. Open );
Byte [] B = new byte [fs. Length];
FS. Read (B, 0, (INT) fs. Length );
FS. Close ();
Context. response. outputstream. Write (B, 0, B. Length );
}
Public bool isreusable
{
Get
{
Return true;
}
}
}
// Handler that generates the verification code
Class codehandler: ihttphandler
{
Public bool isreusable
{
Get
{
Return true;
}
}
Public void processrequest (httpcontext context)
{
Image B = new Bitmap (50, 20 );
Graphics G = graphics. fromimage (B );
Solidbrush sb = new solidbrush (color. White );
Font F = new font ("", 12 );
String STR = "";
Random r = new random ();
For (INT I = 0; I <4; I ++)
{
STR + = R. Next (10 );
}
G. drawstring (STR, F, Sb, 0, 0 );
B. Save (context. response. outputstream, system. Drawing. imaging. imageformat. JPEG );
}
}
Ihttphandler Factory
Class testhandlerfactory: ihttphandlerfactory
{
Public ihttphandler gethandler (httpcontext context, string requesttype, string URL, string pathtranslated)
{

String fname = URL. substring (URL. indexof ('/') + 1 );
While (fname. indexof ('/')! =-1)
Fname = fname. substring (fname. indexof ('/') + 1 );
String cname = fname. substring (0, fname. indexof ('.'));
String classname = "";

Classname = "classlibrary831.codehandler ";
Object H = NULL;
Try
{
// H = new testhandler ();
H = activator. createinstance (type. GetType (classname ));
}
Catch (exception E)
{
Throw new httpexception ("the factory cannot be of the type" + cname + "to create an instance. ", E );
}
Return (ihttphandler) h;
}
Public void releasehandler (ihttphandler handler)
{
}
} (CHE Yanlu)
Configuration File

In this way, testhandlerfactory will execute different httphandler handlers based on different pages of the request.

Httphandler uses session
If you want to use the session in the processing program, you must implement the httphandler irequiressessionstate interface. The irequiressessionstate interface is a null interface, which has no abstract method and is just a flag. This is not verified by examples.

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.