Asp. NET Three Musketeers HttpApplication HttpModule HttpHandler Analysis

Source: Internet
Author: User

We all know that ASP. NET runtime environment, the processing request is done through a series of objects, including Httpapplication,httpmodule, HttpHandler. The reason why these three objects are called ASP. is because they are simply not too important, is completely the backbone of the ASP, responsibility to play AH. Before we get to know them, we need to know the ASP.

Asp. NET pipeline model

Here, for example, IIS6.0 is loaded with Aspnet_isapi.dll in the worker process w3wp.exe . NET Runtime. IIS6.0 introduces the concept of an application pool, a worker process that corresponds to an application pool. An application pool can host one or more Web apps. If HTTP. SYS(HTTP listener, which is part of a Windows TCP/IP network subroutine that is used to continuously listen for HTTP requests) is the first access to the Web app, and after the row is successfully loaded, IIS creates an application domain for the Web app through Appdomainfactory. This means that there are multiple application domains in an application pool that share a worker process resource but do not implicate each other.

A special run-time isapiruntime is then loaded and takes over the HTTP request. Isapiruntime First creates a Isapiworkerrequest object to encapsulate the current HTTP request, and then passes this object to the ASP. NET Runtime HttpRunTime. Since then, HTTP requests have formally entered the ASP.

HttpRunTime Creates a context object HttpContextthat represents the current HTTP request, based on the isapiworkerrequest object. With the creation of the HttpContext object,HttpRunTime creates or obtains an existing HttpApplication using httpapplicationfactory object.

The HttpApplication is responsible for processing the current HTTP request. During the HttpApplication initialization process, ASP. NET loads and initializes the registered HttpModule object based on the configuration file. For HttpApplication , when it handles different stages of an HTTP request, it triggers different events, and HttpModule 's meaning is by registering HttpApplication event, injecting the required operations into the entire HTTP request processing process.

Finally, the processing of HTTP requests is done in HttpHandler , and different resource types correspond to different types of HttpHandler.

Overall processing process:

The processing flow after abstraction:

HttpApplication

HttpApplication is the core of the entire ASP. NET infrastructure, and it handles the HTTP requests that are distributed to it.

When you mention HttpApplication, you have to say global configuration file global.asax. The Global.asax file provides a global class derived from HttpApplication for each Web application. The class contains event handlers, such as Application_Start.

Each Web application will have a global instance, which is the only entry for the application. We know that when an ASP. NET application starts, the ASP. NET runtime calls only once Application_Start. This seems to imply that there is only one global object instance in our application, but not just one HttpApplication object instance.

Asp. The NET runtime maintains a pool of HttpApplication objects. When the first request arrives, ASP. NET creates multiple HttpApplication objects at once and places them in the HttpApplication object pool, and then selects one of the objects to process the request. When a subsequent request arrives, the runtime obtains a HttpApplication object from the pool to pair with the request. The object is associated with the request, and only the request is completed until the request is processed. When the request is complete, the HttpApplication object is not recycled, but is returned to the pool so that it can be pulled out later to serve other requests. By using the HttpApplication object to process the request, the HttpApplication object can only process one request at a time so that its members may store data for each request. Let's take a look at the members of HttpApplication.

As we mentioned before, the HttpApplication object is created by httpruntime based on the context object of the current HTTP request HttpContext or fetched from the pool, and during the HttpApplication initialization process, ASP. NET loads and initializes the registered HttpModule object based on the configuration file. The context property in HttpApplication (an instance of the HttpContext (context) Class) and the Modules property (the collection of HttpModule modules that affect the current application) are used to store them. They are also mentioned in the HttpModule later.

HttpApplication processing the entire life cycle of a request is a relatively complex process, why is it called complexity? Because there are a large number of request-triggered events in the HttpApplication class, the corresponding events are triggered at different stages of the request processing.

We can register the corresponding event via HttpModule and inject the processing logic into a phase of the HttpApplication processing request. It is important to note that events starting with beginrequest, not every pipeline event will be triggered. Because throughout the process, you can call Response.End () or have unhandled exceptions at any time to end the process prematurely. In all events, only the EndRequest event is bound to be triggered, and (partially module) beginrequest may not be triggered. We'll mention that in the HttpModule later.

The HttpApplication class is an important Init method and a Dispose method, which can be overloaded with all two methods. The timing of their invocation is:

The Init method is called after Application_Start, and Dispose is called before Application_End, and Application_Start is fired only once during the lifetime of the entire ASP. For example, when IIS is started or when a Web site is started), similar application_end are called only when an ASP. NET application shuts down (such as when IIS stops or when the site stops).

HttpModule

In the previous tutorial we explained the ASP. NET pipeline model and the HttpApplication object (where pipeline events). Now let's look at HttpModule.

We all know that ASP. NET height is extensible, so what is the achievement of the high scalability of ASP. HttpModule is a must. HttpModule during the initialization process, some callback operations are registered to the HttpApplication corresponding event, at a certain stage of the HttpApplication request processing life cycle, the corresponding event is triggered, Callback operations that are registered through HttpModule are also executed.

All HttpModule implements the IHttpModule interface, which is directly involved with HttpApplication. An HttpApplication object was accepted in its initialization method init (), which made it very easy to register the event.

After I learned about the HttpModule, I couldn't help but to make a surprise, this is not face-oriented (AOP) it!!! We can think of HttpModule as an HTTP request interceptor that, after intercepting an HTTP request, modifies the context in which it is being processed, then returns control to the pipeline and, if there are other modules, resumes processing, until all modules collections (mentioned earlier, exist in HttpApplication) are "cool" until the end of the HttpModule (poor HTTP requests are given to each HttpModule round x). It is this type of httpmodule that is similar to the interceptor pattern, with the HttpApplication pipeline event giving ASP. NET a high degree of scalability.

Unlike HttpHandler for a request file, HttpModule maps the request to the specified handler for all request files, and these processes can occur in any one of the events in the request pipeline. This means that you subscribe to which event, which happens in that event, after processing the next event of the event that you have subscribed to, and of course you can terminate all events to run the last event directly, meaning that he can not give HttpHandler a chance.

In the previous two paragraphs we mentioned that HttpModule for all requests, processing can occur in any one event in the request pipeline. And all HttpModule in the Modules collection are executed in turn for request processing. This naturally allows us to pay attention to performance issues when using powerful HttpModule, to trigger which event handling is not required, and to have strict control over which event handling is triggered. To not let the program load, not worth the candle.

Asp. NET has a lot of httpmodule built in. We open the C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config folder under the Webconfig file, you can find such a configuration:

These are the HttpModule configurations built into ASP. The reason why you should put it here is simple. The configuration here is the default and basic configuration of the. NET framework, and if it is to be configured in the Webconfig file for each project, it is bound to complicate the configuration of the project, so the unification is placed here for configuration.

As for the role of the HttpModule configuration in the nodes, we have also mentioned above. As we talked about earlier, during the HttpApplication initialization process, ASP. NET loads and initializes the registered HttpModule object based on the configuration file . The registered HttpModule object is initialized and stored in the HttpApplication modules attribute. The specific initialization of which HttpModule objects, of course, is related to these configurations.

Although there are many HttpModule built into ASP. NET, we can implement custom HttpModule to give expansion to meet the needs. Let's implement the custom HttpModule ourselves:

First we create a MVC5 controller Defaultcontroller and then create a view index in the controller. The page shows Hello world.

Next we create a custom HttpModule (mymodule):

namespace WebApplication{    public class MyModule : IHttpModule    {        public void Dispose()        {            throw new NotImplementedException();        }        public void Init(HttpApplication context)        {            context.BeginRequest += new EventHandler(BeginRequest);            context.EndRequest += new EventHandler(EndRequest);        }        void BeginRequest(object sender, EventArgs e)        {            ((HttpApplication)sender).Context.Response.Write("

We registered the HttpApplication pipeline events beginrequest and endrequest separately in the initialization method init. Registered events output different text in the response.

Finally, do not forget to configure in the Webconfig file, of course, this webconfig file refers to the webconfig of your project. We need to tell ASP what we have to deal with HttpModule, or we'll kill it and he won't know our custom HttpModule.

The important thing to note here is that in IIS6 and IIS7 Classic mode, we need to configure this:

<system.web>  <add name="MyModule" type="WebApplication.MyModule,WebApplication"/>  </system.web>

type="WebApplication.MyModule,WebApplication"In theWebApplication.MyModule

Refers to a WebApplication class under a namespace MyModule , followed by the WebApplication name of the assembly in which it is located.

In IIS7 integration mode, this configuration is required:

<system.webServer> <modules> <add name="MyModule" type="WebApplication.MyModule,WebApplication"/> </modules></system.webServer>

Otherwise, the following error will be reported:

Everything is ready. To start the project Request/default/index page:

It can be found that our custom HttpModule play a role. As we mentioned earlier, the Modules collection (previously mentioned, which exists in HttpApplication) will trigger its own registration event when it executes to the appropriate pipeline event. Let's try it out.

Let's build a custom HttpModule (yourmodule):

namespace WebApplication{ public class YourModule : IHttpModule { public void Dispose() { throw new NotImplementedException(); } public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(BeginRequest); context.EndRequest += new EventHandler(EndRequest); } void BeginRequest(object sender, EventArgs e) { ((HttpApplication)sender).Context.Response.Write("

Then configure Webconfig to tell ASP. We build a custom HttpModule, you have to do it for me.

<system.webServer> <modules> <add name="MyModule" type="WebApplication.MyModule,WebApplication"/> <add name="YourModule" type="WebApplication.YourModule,WebApplication"/> </modules></system.webServer>

Finally start the project Request/default/index page:

The result is exactly the same:HttpModule will process the request sequentially until all modules collections (previously mentioned, existing in HttpApplication) are processed .

So how does HttpModule control the order in which requests are processed? We can change the order of the Webconfig configurations.

<system.webServer> <modules> <add name="YourModule" type="WebApplication.YourModule,WebApplication"/> <add name="MyModule" type="WebApplication.MyModule,WebApplication"/> </modules></system.webServer>

That is to say, the processing order of HttpModule is based on the order of the configuration, there is no priority .

HttpHandler

Unlike HttpModule for all request files, HttpHandler is mapped to the specified handler for a file of a certain type. In other words, the actual processing of the request is done in HttpHandler, and the previous treatment is assisted. But not every request HttpHandler have the opportunity to take over, auxiliary (HttpModule) also can not give HttpHandler opportunity.

All HttpHandler implements the IHttpHandler interface, where the method ProcessRequest provides the implementation to handle the request. That is, the request processing is played here, provided that the auxiliary (HttpModule) to give the opportunity, we will also write an example to play a play.

As with HttpModule, the HttpHandler type establishes a mapping relationship to the request path pattern, which is also required through the configuration file. In the Webconfig file under the C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config folder, you can also find the HttpHandler configuration that is built into ASP.

Asp. The default HttpHandler mapping operation in net occurs before the HttpApplication Postmaprequesthandler event, which is configured by default. There is also a way of mapping that we can call the current HttpContext Remaphandler method to map a HttpHandler object to the current HTTP request. If the Remaphandler method is not called or if the parameter passed in is NULL, the default HttpHandler mapping operation is performed. It should be noted that the purpose of mapping through the Remaphandler method is to skip the default mapping operation directly, whereas the default mapping operation is triggered before the HttpApplication Postmaprequesthandler event. So it makes sense to call the Remaphandler method before this.

public sealed class HttpContext : IServiceProvider, IPrincipalContainer{   public void RemapHandler(IHttpHandler handler);  }

Below we write ourselves with a custom HttpHandler play, we sometimes have such a demand, their own images only want to be accessed in their own site, in other sites or browsers directly open can not be normal access. So HttpHandler is very suitable for this kind of scene processing, we take the JPG format picture as an example.

First create a custom HttpHandler (jpghandler):

  namespace webapplication{public class Jpghandler:ihttphandler {public bool Isreusab            Le {get {return false; }} public void ProcessRequest (HttpContext context) {context.            Response.ContentType = "Image/jpg"; If Urlreferrer is empty, a default 404 picture if (context) is displayed. Request.urlreferrer = = NULL | | Context. Request.UrlReferrer.Host = = null) {context.                Response.WriteFile ("/error.jpg");            Return } if (context. Request.UrlReferrer.Host.IndexOf ("localhost") < 0) {context.                Response.WriteFile ("/error.jpg");            Return }//Gets the file server-side physical path string fileName = Context. Server.MapPath (context.            Request.filepath); Context.        Response.WriteFile (FileName); }    }}

Then we add two images below the site to do the test, when the picture does not display properly when the default display error Picture:

testing, we request index.jpg resources directly in the browser.

The effect is not ah, in the browser directly request Index.jpg resources should be displayed error picture ah. What's the reason? Don't forget we need to tell ASP. We've customized the HttpHandler, we didn't configure it, and ASP. After the configuration, try again.

<system.webServer>          <add name="jpg" path="*.jpg" verb="*" type="WebApplication.JPGHandler, WebApplication"/>    </system.webServer>

The effect is right, we want it. About cross-domain picture access We do not test, interested in the words can try it yourself.

We mentioned earlier that the HttpHandler default mapping method is through configuration, then we try again non-default way, through the Httpcontextd Remaphandler method.

It's time to assist (HttpModule) to help, because the pipeline event needs to be registered in HttpModule. It is mentioned earlier that it makes sense to call the Remaphandler method before the Postmaprequesthandler event. beginrequest event before the Postmaprequesthandler event, we call the Remaphandler method in the beginrequest event.

namespace WebApplication{    public class MyModule : IHttpModule    {        public void Dispose()        {            throw new NotImplementedException();        }        public void Init(HttpApplication context)        {            context.BeginRequest += new EventHandler(BeginRequest);                    }        void BeginRequest(object sender, EventArgs e)        {            ((HttpApplication)sender).Context.RemapHandler(new JPGHandler());        }    }}

Then we need to configure MyModule in Webconfig, commenting out Jpghandler.

Finally start the project, access the Index.jpg resources, the results are not unexpected, and the default way through the configuration, our custom HttpHandler has the effect.

Let's try again. Is it really meaningless to call the Remaphandler method after the Postmaprequesthandler event?

We put the Remaphandler method call into the acquirerequeststate event, and theacquirerequeststate event is Postmaprequesthandler the first event after the event.

namespace WebApplication{    public class MyModule : IHttpModule    {        public void Dispose()        {            throw new NotImplementedException();        }        public void Init(HttpApplication context)        {            context.AcquireRequestState += new EventHandler(AcquireRequestState);        }         void AcquireRequestState(object sender, EventArgs e)        {            ((HttpApplication)sender).Context.RemapHandler(new JPGHandler());        }    }}

Then start the project and then access the index.jpg resource.

We have found that the ASP has given us a limit, and we have not given us any chance to make mistakes! So how do you implement the call order qualification within ASP? We can look at the source code through Ilspy.

Circled Red Section, whenever Remaphandler executes, it will place the current method in the event (in the Asp,net pipeline model we mentioned with the creation of HttpContext object,HttpRunTime will take advantage HttpApplicationFactory creates or obtains an existing HttpApplication object,HttpApplication object contains a HttpContext property, so it is possible to do this) and an enumeration (for example, an enumeration encoding of pipeline events in order), if greater than or equal to this enumeration (Postmaprequesthandler event), The description is a mapping made after the Postmaprequesthandler event, and an exception is thrown.

Summarize

Understanding Mastering the Httpapplication,httpmodule, HttpHandler these does not make us a good, but the pipeline model and the implementation of the high scalability of the ASP is useful to us. Then we must learn to do their own hands-on experience, do not believe any authority, to believe only their own hands and their eyes. I hope you will read this article, the mind can always remember such a picture is OK.

Because my ability is limited, so the error in the text is inevitable, I hope you correct and put forward valuable suggestions.

Reference: "The ASP. NET MVC 5 Framework"



The thing about the code.
Source: http://songwenjie.cnblogs.com/
Statement: This article for Bo Master Learning sentiment Summary, the level is limited, if improper, welcome correction. If you think it's good, just click on the "recommend" button below, thanks for your support. Reprint and quote please specify the source.
Public Number:


Asp. NET Three Musketeers HttpApplication HttpModule HttpHandler Analysis

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.