HttpModules and httphandlers[reproduced in Web. config]

Source: Internet
Author: User

Asp. NET process for request processing:

When a *.aspx file is requested, the request is intercepted by the Inetinfo.exe process, and after it determines the suffix (aspx) of the file, the request is forwarded to the aspnet_isapi.dll,aspnet_ ISAPI.dll sends the request through the HTTP pipeline (HTTP PipeLine) to the Aspnet_wp.exe process, processes the request through httpruntime in the Aspnet_wp.exe process, and returns the result to the client after processing.

Inetinfo.exe process: is the process of WWW service, IIS service and ASPNET_ISAPI. DLLs are hosted in this process.

Aspnet_isapi. DLL: Is the Win32 component that handles. aspx files. In fact, the IIS server is only aware of. html files, and when the IIS server discovers that the requested file is an. aspx file, the IIS server gives it to aspnet_isapi.dll for processing.

Aspnet_wp.exe process: The ASP. NET Framework process, which provides a managed environment for. NET runs, and the CLR (Common Language Runtime) for. NET is hosted in this process.

The ASP. NET Framework processes an HTTP request:

Httprequest-->inetinfo.exe-->aspnet_isapi.dll-->aspnet_wp.exe-->httpruntime-->httpapplication Factory-->httpapplication-->httpmodule-->httphandler factory-->httphandler--> Httphandler.processrequest ()

Asp. NET request processing is based on the pipeline model, the pipeline model is composed of multiple HttpModule and HttpHandler, ASP. NET transmits the HTTP request to each HttpModule in the pipeline, finally is HttpHandler processing, after processing completes, again passes through the pipeline the HTTP module, returns the result to the client. We can intervene in the processing of requests in each httpmodule.

Note: During the processing of HTTP requests, only one httphandler can be called, but multiple httpmodule may be called.

When the request arrives at HttpModule, the system does not actually process the request, but we can attach some additional information before the request is delivered to the processing center (HttpHandler), or intercept the request and do some extra work, or terminate the request. After HttpHandler finishes processing the request, we can then re-process the result of the request processing back to the client in the corresponding HttpModule.

HttpModule

The HTTP module is a class that implements the System.Web.IhttpModule interface.

Declaration of the IHttpModule interface:

public interface IHttpModule

{

void Init (HttpApplication context);

void Dispose ();

}

Init method: Called automatically when the system initializes, this method allows the HTTP module to register its own event handlers with the events in the HttpApplication object.

Dispose method: This method gives the HTTP module the opportunity to perform cleanup before the object is garbage collected. This method generally eliminates the need to write code.

The HTTP module can register the following sequence of events with the System.Web.HttpApplication object:

AcquireRequestState This event is raised when the ASP. NET runtime is ready to receive the dialog state of the current HTTP request.

AuthenticateRequest This event is raised when the ASP. NET runtime prepares to authenticate the user.

AuthorizeRequest This event is raised when the ASP. NET runtime prepares authorized users to access resources.

BeginRequest This event is raised when the ASP. NET runtime receives a new HTTP request.

Disposed This event is raised when ASP. NET completes the processing of the HTTP request.

This event is raised by EndRequest before the response is sent to the client.

Error raises this event when an unhandled exception occurs during the processing of an HTTP request.

PostRequestHandlerExecute This event is raised when the HTTP handler finishes execution.

PreRequestHandlerExecute This event is raised before ASP. NET starts executing the HTTP request handler. After this event, ASP. NET forwards the request to the appropriate HTTP handler.

Presendrequestcontent raises 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 to the page output for all pages. such as generic menus, header information, or foot information.

Presendrequestheaders raises this event before ASP. NET sends HTTP response header information to the client. This event allows us to change the contents of the header before it reaches the client. We can use this event to add cookies and custom data to the header information.

ReleaseRequestState This event is raised when ASP. NET ends the execution of the request handler that is being searched.

Resolverequestcache we raise this event to decide whether we can end the request using the content returned from the output buffer. This depends on how the Web application's output buffers are set.

Updaterequestcache This event is raised when ASP. NET completes the processing of the current HTTP request and the output is ready to be added to the output buffer. This depends on how the output buffer for the Web application is set.

Above so many events, we may seem to be somewhat dizzying, but it doesn't matter, see below step by step.

HttpModule life cycle

The following is the order in which events are triggered:

The event between BeginRequest and PreRequestHandlerExecute is triggered before the server performs HttpHandler processing.

The event between PostRequestHandlerExecute and Presendrequestcontent is triggered after the server performs handler processing.

Let's take a look at how to use HttpModule to implement our everyday applications:

HttpModule inserts itself into the ASP. NET request processing pipeline by registering in certain events. When these events occur, the ASP. NET calls to the appropriate HTTP module so that the module can process the request.

1. Add some notes or descriptive text to each page dynamically:

Some sites each page will pop up an ad or on each page in an annotated form (<!---->) to add the site's copyright information. If in each page to teach such JS code, for a larger site, this JS code writing and maintenance is a very tedious and boring work.

With HttpModule, we can solve this problem very simply. HttpModule is a necessary way for a client to make a request to the client to receive a server response. We can add this comment text to the page text after the server finishes processing the request and before sending the response text to the client. In this way, each page request is appended with the comment text.

In which event should this code be implemented? Any event between PostRequestHandlerExecute and Presendrequestcontent is possible, but I prefer to write code in the EndRequest event.

First step: Create a class library ClassLibrary831.

Step Two: Write a class to implement the IHttpModule interface

Class Testmodule:ihttpmodule

{

public void Dispose ()

{

}

public void Init (HttpApplication context)

{

}

}

Step three: Register the endrequest event in the Init event and implement the event handling 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 ("<!--this is the text that is dynamically generated for each page. --grayworm--> ");

}

}

Fourth Step: Register this HttpModule module in Web.conofig

<add name= "Testmodule" type= "classlibrary831.testmodule,classlibrary831" ></add>

Name: module names, typically class names

Type: There are two parts, the first half is the full name of the namespace and the class name, the second part is the assembly name, and if the class is placed directly in the App_Code folder, the program name is App_Code.

This way, after the Web site is adding a reference to the class library, running each page will find that its source file will include "<!--this is the text that each page will generate dynamically. --grayworm--> "this sentence. You can also add the JS code to the same method.

2. Identity check

When you log in, the login is successful, the user name is generally stored in the session, in each of the other pages of the Page_Load event to check whether the user name in the session, if it does not exist, it means that the user is not logged in, do not let it access the content.

In a larger program, this is too clumsy, because you almost have to include in each page the detection session code, resulting in difficult to develop and maintain. Now let's see how we can use HttpModule to reduce our workload.

Since we are going to use the contents of the session here, we can only write code in the AcquireRequestState and PreRequestHandlerExecute events. Because only these two events can be accessed in the HttpModule session. Here we choose the PreRequestHandlerExecute event to write the code.

First step: Create a class library ClassLibrary831.

Step Two: Write a class to implement the IHttpModule interface

Class Testmodule:ihttpmodule

{

public void Dispose ()

{

}

public void Init (HttpApplication context)

{

}

}

Step three: Register the PreRequestHandlerExecute event in the Init event and implement the event handling 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)//is the login page, not the login page, then enter {}

{

if (ha. context.session["user"] = = NULL)//Whether the Session has a user name, if empty, turn to the login page.

{

Ha. Context.Response.Redirect ("login.aspx?source=" + path);

}

}

}

}

Fourth Step: Add the following code to the "Login" button on the Login.aspx page

protected void Button1_Click (object sender, EventArgs e)

{

if (true)//determine if the user name password is correct

{

if (request.querystring["source"]! = NULL)

{

string s = request.querystring["source"]. ToLower ().    ToString (); Take out which page to turn from

session["user"] = Txtuid.text;

Response.Redirect (s); Go to the page the user wants to go to

}

Else

{

Response.Redirect ("main.aspx"); Default Steering Main.aspx

}

}

}

Fifth Step: Register this HttpModule module in Web.conofig

<add name= "Testmodule" type= "classlibrary831.testmodule,classlibrary831" ></add>

3, multi-module operation

If more than one httpmodule is defined, the order in which custom HttpModule are introduced in the Web. config file determines the order in which multiple custom HttpModule handle the takeover of an HTTP request.

HttpHandler

HttpHandler is the processing center of the HTTP request, which actually compiles and executes the server page requested by the client, and appends the processed information to the HttpModule in the HTTP request stream.

HttpHandler is different from HttpModule, once you define your own HttpHandler class, the relationship between the HttpHandler of the system will be "overwrite".

IHttpHandler Interface Declaration

public interface IHttpHandler

{

BOOL IsReusable {get;}

public void ProcessRequest (HttpContext context); Request handler function

}

Example: Writing a picture on a hard drive to a page in a streaming way

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

<add verb= "*" path= "*" type= "classlibrary831.testhandler,classlibrary831" ></add>

Verb property: Specifies the HTTP actions supported by the handler. *-supports all HTTP actions; " Get "-support for Get operation;" Post "-support post operation;" GET, POST "-supports two operations.

Path property: Specifies the path and file name (which can contain wildcards) that require the handler to be called. "*", "*.aspx", "showimage.aspx", "test1.aspx,test2.aspx"

Type property: Specifies the actual type of the handler or handler factory as a combination of the namespace, class name, and assembly name. Asp. NET runtime first searches the DLL in the bin directory and then searches in the GAC.

The effect of running the program is that any page of the site will display a worm.jpg picture. How do I get only one page (default21.aspx) to perform the ProcessRequest method in HttpHandler? The simplest approach is to set the path configuration information to default21.aspx in the Web. config file.

According to this example, you can consider how to write "Verification code".

IHttpHandler Factory

The role of IHttpHandlerFactory is to manage the IHttpHandler. The function of the factory please see http://hi.baidu.com/grayworm/blog/item/4a832160f8c9de46eaf8f8c1.html "

Declaration of the IHttpHandlerFactory interface:

public interface IHttpHandlerFactory

{

IHttpHandler GetHandler (HttpContext context,string requesttype,string url,string pathTranslated);

void Releasehandler (IHttpHandler handler);

}

GetHandler returns an instance of the class that implements the IHttpHandler interface, Releasehandler enables the factory to reuse an existing handler instance.

Example: Two uses IHttpHandlerFactory to implement a call to a different HttpHandler.

There are two HttpHandler: the HttpHandler that displays the picture on the page and the handler to generate the verification code

Handler to display a picture on a 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;

}

}

}

Generate verification code for handler

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 ("Arial", 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 ("Factory cannot create an instance for type" + CNAME + ".) ", e);

}

Return (IHttpHandler) H;

}

public void Releasehandler (IHttpHandler handler)

{

}

} (Che Yanlu)

Configuration file

<add verb= "*" path= "default21.aspx,default22.aspx" type= "classlibrary831.testhandlerfactory,classlibrary831" ></add>

This way the testhandlerfactory executes different HttpHandler handlers based on the different pages requested.

HttpHandler using Sessions

If the session is to be used in a handler, the HttpHandler must be implemented IRequiresSessionState interface, IRequiresSessionState interface is an empty interface, it has no abstract method, just a token. This is not an example to verify

Asp. NET when processing HTTP request, using pipeline (pipeline) method, the request is processed by each HttpModule, and then arrives httphandler,httphandler after processing, is still processed by each HttpModule in pipeline, and the HTML is finally sent to the client browser.

Several very important objects are involved in the life cycle: Httphandler,httpmodule,ihttphandlerfactory, whose execution (order) is roughly executed: The client sends a page request and is intercepted by a process in IIS.  It calls different page handlers (.asp->asp.dll;), depending on the page suffix (. aspx) of the application. . Aspx->isapi.dll). While the page handler is in the process of processing, it undergoes httpmodule,httphandler processing: The former HttpModule for the processing of some events before and after the page processing, The latter httphandler the processing of real pages.

As previously mentioned, HttpModule will process the page before and after the page is processed, so it will not affect the actual page request. It is usually used to add some information (such as a copyright notice) to the head or tail of each page. Have seen some free space, our page uploaded, browse the time found that in each page of the head and tail more than a lot of small ads ..., if you understand the principle of HttpModule, It's not hard to do this.

The difference between IHttpModule and IHttpHandler

1. Sequencing. First IHttpModule, then IHttpHandler. Note: module depends on which event you are responding to, some of which are running before handler, some are running after handler

2. On the processing of the request:

IHttpModule is a size-all type that calls to it regardless of what file the client requests, such as Aspx,rar,html's request.

IHttpHandler is a picky eater, and only the file types that are registered by ASP (for example, Aspx,asmx, and so on) will be called.

3.IHttpHandler generates the content of the response according to your request, ihttpmodule the request, such as validation, modification, filtering, and so on, and can also handle the response

Asp. NET system itself is configured with many HttpHandler and HttpModule to handle ASPX and so on. NET Standard, as well as the standard event handling in these paging files. You can see these configurations by looking at the httphandlers and httpmodules nodes in the Web. config file under the%system%/microsoft.net/framework/v2.0.50727/config directory. If you are interested, you can use reflector to view the related classes and methods in the. NET System. NET and what to do with it.

.  NET also provides a set of mechanisms to develop custom HttpHandler and httpmodule that can be used to intercept the HttpRequest and complete the custom processing. HttpModule inherits the System.Web.IHttpModule interface and implements its own HttpModule class. There are two ways to implement an interface: Init and Dispose. In Init, you can add events that need to be intercepted, Dispose is used for resource deallocation, and if you create your own resource object in Init, release it in Dispose.

Namespace MyModule

{

public class Myhttpmodule:ihttpmodule

{

Public Myhttpmodule ()

{

}

The Init method is used to register the HttpApplication event.

public void Init (HttpApplication r_objapplication)

{

R_objapplication.beginrequest + = new EventHandler (this. beginrequest);

}

public void Dispose ()

{

}

private void BeginRequest (object r_objsender, EventArgs R_objeventargs)

{

HttpApplication objapp = (HttpApplication) R_objsender;

ObjApp.Response.Write ("The URL you requested is" + ObjApp.Request.Path);

}

}

}

Copy the compiled DLL file to the bin directory of the Web project, and configure it in the Web. config file system.web node of the website:

This inserts the custom HttpModule class Myhttpmodule into the pipeline of the current web HttpModule. The main function of HttpModule is to intercept the various events of application, and to complete their own processing in these events. In fact, if you develop some projects, directly in the Global.asax processing is enough.      If you are developing a framework or some aspect of a component, you need to add processing to the event, develop a custom HttpModule, avoid using the framework or components, and manually add code to the Global.asax. Now think of the purpose of developing custom HttpModule, there are global identity/authorization verification, custom site access/operation log records, in the management/debugging for the purpose of monitoring the site tracking and so on. Of course, if the framework is developed in conjunction with a custom HttpHandler, HttpModule can be used for some other special processing.

<add name= "test" type= "Myhttpmoduletest.myhttpmodule,myhttpmodule"/>

Note to be case-sensitive, because Web. config is case-sensitive as an XML file. "Type=myhttpmoduletest.myhttpmodule,myhttpmodule" tells us

The HTTP request will be forwarded to the Myhttpmoduletest.myhttpmodule class located in the MyHttpModule.dll file for processing.

The HttpHandler is a complete interception of HTTP request.

First, inherit the System.Web.IHttpHandler interface and implement your own HttpHandler class. The ProcessRequest method and the IsReusable property of the interface must be implemented. The ProcessRequest method completes the processing of each HTTP request, sending the HTML of the processing result to the output cache. The IsReusable property is called by the. Net framework to determine whether the instance of this HttpHandler can be reused for other request processing of the same type.

If you need to read or write session values in your HttpHandler class, you need to inherit an interface irequiressessionstate. There is no method for this interface, just a token interface. After inheriting this interface, you can access the session in your HttpHandler, and you can write values in the session.

Namespace MyHandler

{

public class Myhttphandler:ihttphandler, IRequiresSessionState

{

Public Myhttphandler () {}

public bool IsReusable

{

get {return true;}

}

public void ProcessRequest (HttpContext context)

{

HttpResponse Objresponse = context. Response;

Objresponse.write ("

This request was handled by Myhttphandler

");

}

}

}

Copy the compiled DLL file to the bin directory of the Web project.

Next, let's test the Myhttphandler. We configured a file type with a. cc suffix for IIS to handle with the Myhttphandler we wrote.

First, in the config configuration of the IIS site, add a application extention mapping item that handles the. cc suffix name.

Then, configure it in the Web. config node node of the project:

Myhttphandler, MyHandler "/>

The verb property configures this httphandler to handle those HTTP methods, such as GET, post, etc., if all methods are handled, use *. The Path property configures HttpHandler which files are processed, such as myfile.cc, and *.cc if all. cc files are processed.

In this way, access to all. CC type files on this site is handled by Myhttphandler. You can see the test results by using the http://localhost/site virtual directory/a.cc to access the test site. Of course, a.cc This file does not exist on the Web server.

The use of HttpHandler is more typical. NET of Web MVC Open source project Maverick. Maverick uses a dispatcher class to intercept all HTTP requests, and he submits the request to the Web server with. m as the suffix, and in dispatcher, removes the suffix of. m, extracts the command Name, This command name then loads the processed flow from the configuration file, forming a chain, sequentially processing each command and view on the chain, and processing results for each command and view may select different processing branches in chain , each processed step will output the HTML written to the response in the cache of the processed results.

Overall, Maverick's framework concept is very good, but there are obvious flaws, there will be time to write the details of its architecture and the need for improvement.

In a word, combining HttpModule, HttpHandler, and using AJAX to encapsulate the client is a great place to improve the development of Web projects.

ASP. NET HttpHandler implements URL rewriting

We often see a lot of Web site access to the article when the use of ***.html or ***.shtml (such as the blog's Log access effect), when this write file on the server does not exist, then why this effect, is because the Web server on the URL to perform a rewrite, the access to the URL based on a specific format to rewrite the internal access to the page to achieve, it is easy to understand the benefits of the user, while the search engine can also better revenue your site, of course, there are many other benefits, there is no introduction here.

This article is about using ASP. HttpHandler implementation of the URL rewrite, the principle of implementation of it, see here, this program can handle any URL, because I used the URL in the program, only the Access file name is a number of processing, and the internal execution of a new page, and output data, the code is as follows:

public void ProcessRequest (HttpContext Context)

{

try {

Statement of request

HttpRequest Request = context.request;

The absolute path of the URL to take the route

string Url = Request.Url.AbsolutePath;

The number of start character intervals for the Web file accessed

int regstart = Url.lastindexof ("/") + 1;

Affirm that a Web file name is determined to be all numbers

Regex Reg = new Regex (@ "/d+");

Match with regular expressions

if (Reg.ismatch (URL, Regstart))

{

If the Web file name is a number, the decision is to query the relevant article, executing the specified page Context.Server.Execute ("~/permalink.aspx?id=" + reg.match (URL, Regstart). Value);

}

}

Catch

{

Context.Response.Redirect (Context.Request.Url.ToString ());

}

}

Of course, the first thing you need to do is to build a class and inherit from IHttpHandler, and then copy the code into and compile it. In order to use this feature in a Web project, you need to add the following statement to the website. config:

<add verb= "*" path= "*.shtml" type= "Httphandle.urlrewrite"/>

Also, to configure the Web project in IIS, in the properties of the Web project, in the Home Directory tab, change the Execute permission to "script and executable", then open the configuration, add the extension of the file format that needs to be rewritten in the application extension, all right, the implementation, only owes to run.

Transferred from: http://blog.csdn.net/zhaili1978/article/details/6335595

HttpModules and httphandlers[reproduced in Web. config]

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.