Switch: ASP. NET uses the pipeline model (piplelines) to process HTTP requests

Source: Internet
Author: User

 

Most people think that ASP. NET is just a page-use a template to create an HTML page and return it to the browser. However, this is only a small aspect of ASP. NET's use of the HTTP pipeline model to process web programs. The pipeline model is similar to a web service framework that processes ASP. NET pages on the server. As an advanced ASP. NET developer, you must understand how the pipeline model works. This article explains and explains how the HTTP pipeline model processes HTTP requests. I. Pipeline Object ModelThe MPs queue model is used to process HTTP requests in the system. Web namespace. The structure of a general pipeline model is-1. Before the pipeline model starts running, HTTP requests are first transmitted to an instance of the httpruntime class, then the httpruntime object checks the request and finds out the application that the request is sent to (in the pipeline program's view, a virtual directory is an application ). The pipeline model then uses an httpapplicationfactory object to locate or create an httpapplication object to process this request. An httpapplication can contain a series of HTTP
Module object (derived from the ihttpmodule interface ). As a filter, HTTP modules can check and modify the content of HTTP requests and responses when passing through the pipeline model. Then the httpapplication object uses HTTP handler factory to locate or generate an HTTP handler object. HTTP handlers is the last step of HTTP communication. It is mainly used to process request and response information ). Note: HTTP handlers and handler factory are derived from the ihttphandler interface and ihttphandlerfactory interface respectively. Figure-1 An httpapplication includes its modules and handler, which can only process one request at a time. If multiple request requests reach the same application at the same time, multiple httpapplication objects will be used. The pipeline model uses an httpcontext object to describe every pair of request/response information. This object is passed back and forth between httpapplicaiton and handler. Each module can also access the current httpcontext. The httpcontext object uses attributes to describe the HTTP request and Response Information (create the httprequest class and httpresponse class respectively). Similarly, httpcontext objects can also use attributes to describe security information and each call, session, and application. Figure 2Shows some common attributes of the httpcontext class. The HTTP pipeline model of ASP. NET is extensible. You can implement your own HTTP module, handler, and handler factory. You can also inherit the httpapplication class directly.
Attribute name Description
Application Request information of each application
Application Instance Application Object Processing request
Cache Cache Information of each application
Handler Handler object processing request
Items Information of each request
Request HTTP Request Information
Response HTTP Response Information
Server Utility Functions
Session Per-user cross-request State
User User Information
Figure 2: common attributes of the httpcontext class Ii. Pipeline Processing ModelThe ASP. net http pipeline program runs on IIS to receive the request passed to the process (completely transmitted to other web servers ). When IIS receives an HTTP request, it first checks the file extension through the target URL. If the file name is associated with executable code, IIS will call these codes to process request requests. The file extension is mapped to executable code stored in the IIS metabase tag. After ASP. NET is installed, it adds various file extensions to the matabase tag through a dynamic link library aspnet_isapi.dll, including. retrial and. asmx. When IIS receives an HTTP request from a page file, it calls the code in aspnet_isapi.dll to forward the request sent by inetinfo.exe on the iisserver to ASP using a name pipeline. an instance of the net worker process: aspnet_wp.exe. (In Windows Server 2003, the HTTP listener in IIS 6.0kernel-mode allows requestrequest to forward directly from the operating system to the working process without passing through inetinfo.exe .) A worker process uses an httpruntime instance to process request. Figure-3
Demonstrate the complete mechanism. Figure-3http MPs queue processes request requests in the worker process instance. By default, only one worker process can work at a certain time point (If your web server has multiple CPUs, you can configure the MPs queue program to use multiple worker processes ), this is an important change in local IIS. It uses different working processes to isolate different applications. At the same time, the workflow of the MPs queue is completely isolated by the appdomain. You can regard the appdomain as a sub-process in the process. The MPs queue sends HTTP requests to all virtual directories in an appdomain.
Request. In other words, each virtual directory is treated as a separate application. Another important change to local IIS is to allow multiple virtual directories to be part of the same application.
ASP. NET supports many Standard Cyclic working processes, including idle time, the number of requests serviced, the number of requests queues, and the consumption of physical memory. The global. Net configuration file and the machine configuration file initialize these values (like the processmodel element ). When a crosses one of these thresholds instance of aspnet_wp.exe runs a new working process and starts to send a request. The old instance is automatically terminated after it processes the request. Cyclic working processes increase reliability by killing these processes before they consume resources. Iii. Http handlersHTTP handlers is a simple class that inherits from the ihttphandler interface. The code for this class is as follows: interface ihttphandler {// called to process request and generate response void processrequest (httpcontext CTX ); // called to see if handler can be pooled bool isreuseable {Get ;}} handlers can also inherit from the ihttpasynchandler interface, if you want them to support asynchronous calls. The httpapplicaiton object calls the processrequest method and uses handler to process the current HTTP request and generate a response. During this period, the isreuseable attribute will be accessed as a class to determine whether the hanlder can be reused.
Figure 4 Code implements a simple reusable HTTP handle, which can respond to all request requests and return the current time in an XML tag. You can also use the response attribute of the httpcontext object to set the mime attribute of the response information to output your own content.using System;
using System.Web;
 
namespace Pipeline
{
 
 public class TimeHandler : IHttpHandler
 {
    void ProcessRequest(HttpContext ctx)
    {
      ctx.Response.ContentType = "text/xml";
      ctx.Response.Write("<now>");
      ctx.Response.Write(
                   DateTime.Now.ToString());
      ctx.Response.Write("</now>");
    }
    bool IsReuseable { get { return true; } }
 }
}
Figure 4: timehandler

When the HTTP handler class is implemented, it must be configured. The configuration is divided into three phases: first, you should put the compiled code into a place that can be found by the ASP. NET workflow. Generally, compiled. Net files (usually DLL files) should be located in the bin folder under the virtual directory of the Web server or in the global compilation cache (GAC ). Step 2: When an HTTP request arrives, you should let the HTTP pipeline program execute your code. You can add the Figure 5 Apart from implementing the existing client handler, you can also write your own handler factoriey. A handler factoriey is a class that implements ihttphandlerfactory. The configuration method of handler factiory is the same as that of normal handlers. The only difference is that the handler class in the original web. config file will be replaced by the factory class.Iv. Standard handlersSome advanced ASP. NET technologies, such as pages and web services, are directly created through the top-layer HTTP handler. The following is through.

<%@ WebHandler language="C#"
    class="Pipeline.TimeHandler" %>
 
using System;
using System.Web;
 
namespace Pipeline
{
 
 public class TimeHandler : IHttpHandler
 {
    void ProcessRequest(HttpContext ctx)
    {
      // set response message MIME type
      ctx.Response.ContentType = "text/xml";
      // write response message body
      ctx.Response.Write("<now>");
      ctx.Response.Write(
                   DateTime.Now.ToString());
      ctx.Response.Write("</now>");
    }
    bool IsReuseable { get { return true; } }
 }
}
Figure 6

The entity in the second It is worth noting that the pagehandlerfactory, webservicehandlerfactory, and simplehandlerfactory classes cannot compile the. aspx,. asmx, And. ashx files on each request. As an alternative, these compiled code will be cached in a temporary file under the ASP. NET installation directory. And when the source code changes, the code will only be compiled once.

V. Http modulesHTTP handlers is the final part of HTTP Communication. Handler instances are used to receive HTTP requests and generate response responses. HTTP modules acts as a filter to process request and response information when it passes through the MPs Queue (it can be to check and modify the content of this information ). MPs queues can use these HTTP modules to securely implement their underlying processing programs. HTTP modules is a simple class for implementing the ihttpmodule interface: interface ihttpmodule {// called to attach module to app events void Init (httpapplication APP); // called to clean up void dispose ()} when a module is created for the first time, the init method is called by the httpapplication object. It can bind one or more event handlers to the event through the httpapplication object. The code in figure-7 shows how an HTTP module handles the beginrequest and endrequest events of an httpapplication object. In this example, the init method uses the common. NET technology to bind the onbeginrequst and onendrequest of the module to the httpapplication object as the event handle. Onbeginrequest is mainly used to obtain the current storage time and store the time in the Variable Start. Onendrequest is mainly used to calculate the time difference between onbeginrequest and onendrequest and add the time to the client HTTP
Header.
The biggest advantage of the onendrequest method is that the httpapplication object bound to the module actually passed by the first parameter. The current information will be used as an http-context attribute of an httpapplication object by the onendrequest method.

using System;
using System.Web;
 
namespace Pipeline
{
 
 public class ElapsedTimeModule : IHttpModule
 {
    DateTime start;
    public void Init(HttpApplication app)
    {
      // register for pipeline events
      app.BeginRequest +=
          new EventHandler(this.OnBeginRequest);
      app.EndRequest +=
          new EventHandler(this.OnEndRequest);
    }
    public void Dispose() {}
 
    public void OnBeginRequest(object o,
                               EventArgs args)
    {
      // record time when request started
      start = DateTime.Now;
    }
 
    public void OnEndRequest(object o,
                             EventArgs args)
    {
      // measure elapsed time
      TimeSpan elapsed =
              DateTime.Now - start;
 
      // get access to app and context
      HttpApplication app =
              (HttpApplication) o;
      HttpContext ctx = app.Context;
 
      // add custom header to HTTP response
      ctx.Response.AppendHeader(
                   "ElapsedTime",
                   elapsed.ToString());
    }
 }
}
Figure-7 you must configure an HTTP module class between implementation and use. The configuration steps are as follows. First, you should put the compiled module code in the bin folder under the Site Directory on the Web server so that the ASP. NET workflow can find it.
Then you should go to your web. add

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.