asp.net http Runtime composition detailed

Source: Internet
Author: User
Tags file system iis object model terminates thread versions web services hosting
Asp.net| Detailed Introduction

Regardless of the underlying platform, reliability and performance are the main requirements for all WEB applications, although in a sense the two requirements are conflicting. For example, to build a more reliable and robust application, you might want to detach your WEB server from a specific application and make your application work out-of-process. However, if you work in a memory environment that is different from the WEB server process, the application slows down. Therefore, there is a need to take reasonable steps to ensure that out-of-process code runs as quickly as possible.

In building Microsoft? The ASP.net runtime environment is based on the design principle that takes full account of reliability and performance. The resulting ASP.net process model contains two system elements-an in-process connector that exists in the WEB server process, an external worker process. In addition, the ASP.net runtime structure is scalable enough to automatically use any processor selected in multiprocessor hardware. This pattern is called "Web Garden", which enables multiple worker processes to run concurrently, and each process is in a separate processor.

To sum up, the ASP.NET runtime has three main properties:

Complete separation between the application and the ASP.net worker process. The lifetime of the application is never affected by the life of the worker process that provides the service. In other words, when the application starts and is running, the worker process can terminate at any time.
Although ASP.net applications never run in-process within a WEB server, in most cases their overall performance is still close to the performance of an in-process application.

Provides built-in and configurable support for the Web Garden architecture. By simply checking the settings in the configuration file, the worker process can clone itself to take advantage of all CPUs that are closely related to the process. Therefore, in most cases, the scalability you get on a multiprocessor computer will grow linearly. (This is covered in more detail later in this article.) )

This article describes the elements of the ASP.net runtime environment, and then steps through the "long and tortuous" process of turning URL requests into plain HTML text.

Unless otherwise stated, the following descriptions refer to the default process model for ASP.net, Microsoft? The only model in Internet information Services (IIS) 5.x.
Components of a ASP.NET structure

Executing the asp.net application requires the support of the hosting Web server. At Microsoft? Windows? Server platform, the WEB server is represented by an IIS executable file named Inetinfo.exe. The Windows 2000 and above versions of the operating system itself provide a WEB server. But you need to be aware that at Microsoft? In Windows Server 2003, IIS and asp.net are not installed by default and must be added to the system by clicking the Add or Remove Programs applet in Control Panel.

IIS is an unmanaged executable program that provides an extensible model based on ISAPI extension modules and filter modules. By writing such modules, developers can directly manage requests for a specific resource type and receive the current request in each predefined step. Extensions and filters are some DLLs that can export functions with known names and signatures. These plug-in components are registered and configured in the IIS configuration database.
 
Only a handful of resource types that are requested by the client are processed directly by IIS. For example, incoming requests for HTML pages, text files, JPEG, and GIF images are handled by IIS. Requests for Active Server Page (*.asp) files are resolved by invoking an ASP-specific extension module called Asp.dll. Similarly, requests for ASP.net resources (for example, *.aspx, *.asmx, *.ashx) are passed to the asp.net ISAPI extension. The system component is a Win32 dll named Aspnet_isapi.dll. asp.net extensions can handle a variety of resource types, including WEB services and HTTP handler calls.

The asp.net ISAPI extension is a Win32 DLL and does not integrate managed code. It is the control center that receives and assigns requests for various asp.net resources. By design, the module exists in the IIS process and runs under the SYSTEM account with administrator privileges. This account cannot be modified by developers and system administrators. The asp.net ISAPI extension is responsible for invoking the ASP.net worker process (aspnet_wp.exe), which is also responsible for controlling the execution of the request. In addition to scheduling requests, the ASP.net ISAPI monitors the operation of the worker process and cancels the process when performance is reduced to a certain extent.

A worker process is a small piece of Win32 shell code that integrates the common language runtime (CLR) and runs managed code. It is responsible for processing requests for ASPX, ASMX, and ASHX resources. In general, this process has only one instance on a given computer. All currently activated ASP.net applications are running in them, and each application is in a separate AppDomain. However, as mentioned earlier, the worker process supports Web Garden mode, where the same copy of the process runs in a CPU that is closely related to the process. (For more information, see the "Web Garden Model" section later in this article.) )

Communication between ISAPI and worker processes is done using a set of named pipes. Named pipes are a Win32 mechanism for transferring data across process boundaries. As the name suggests, named pipes work the same way as pipelines: enter data at one end and output the same data on the other end. A pipe is established to connect to a local process or to a process running on a remote computer. For local interprocess communication, pipelines are the most efficient and flexible tool in Windows.

To ensure optimal performance, ASPNET_ISAPI uses an asynchronous named pipe to forward requests to the worker process and get a response. On the other hand, the worker process uses a synchronous pipeline when it needs to query information about the IIS environment, that is, the server variable. The Aspnet_isapi module creates a fixed number of named pipes and uses overlapping operations to handle connections at the same time through a small thread pool. When the data exchange operation through the pipeline is finished, the completion routine disconnects the client and uses the pipe instance again to service the new client. Thread pooling and overlapping operations ensure that the performance of the ASP.net ISAPI is at a satisfactory level. However, the ASPNET_ISAPI extension will never handle HTTP requests.

The processing logic of the ASP.NET request can be summed up as the following steps:

When the request arrives, IIS checks the resource type and invokes the asp.net ISAPI extension. If the default process model is enabled, ASPNET_ISAPI queues the request and assigns the request to the worker process. All request data is sent through asynchronous I/O. If the IIS 6 process model is enabled, the request is automatically queued in a worker process (w3wp.exe), which is used to process the IIS application pool to which the application belongs. The IIS 6 worker process does not know anything about ASP.net and managed code, it simply handles *.aspx extensions and loads ASPNET_ISAPI modules. When ASP.net ISAPI runs in the IIS 6 process model, it works differently, loading the CLR only in the context of the W3wp.exe worker process.

When a request is received, the ASP.net worker process notifies the ASP.net ISAPI that it will service the request. Notifications are implemented through synchronous I/O. The synchronization model is used because the request is marked as "executing" in the ISAPI internal request table before the worker process can begin processing it. If a request has been processed by a special worker process, it cannot be assigned to another process unless the original process has been canceled.
Executes the request in the context of the worker process. Sometimes, a worker process may need to recall the ISAPI to complete the request, which is to say enumerate the server variables. In this case, the worker process uses the synchronization pipeline, because it keeps the order of the request processing logic.

When finished, the response is sent to the ASPNET_ISAPI that opened the asynchronous pipe. The requested status is now changed to "done" and will then be deleted from the request table. If the worker process crashes, all requests that are being processed remain "executing" and persist for a period of time. If ASPNET_ISAPI detects that the worker process has been canceled, it automatically terminates the request and releases all the associated IIS resources.

The description above refers to the default ASP.net process model, which is the working model that runs in IIS 5.x. The default mode of work for IIS 6 (provided by Windows Server 2003) also has an impact on the ASP.net process model. When integrated in IIS 6.0, ASP.net 1.1 automatically adjusts its way of working to accommodate the hosting environment. At this point, you no longer need to use the ASPNET_WP worker process, and some of the configuration parameters defined in the Machine.config file are ignored. From a asp.net point of view, the biggest change in IIS 6 is that everything about the request is under ASPNET_ISAPI control and is in the context of the W3wp.exe worker process. The account for the worker process is the account that is set up for the application pool to which the Web application belongs. By default, the account is NetworkService, which is a built-in weak account that is functionally equivalent to the ASPNET.

The worker process is controlled by a feature called Process Recycling (Recycling). Process Recycling has the ASPNET_ISAPI capability to automatically start a new process when the existing process consumes too much memory, responds too slowly, or hangs. When this occurs, the new request is processed by the new instance, which becomes the new active process. However, all requests that are assigned to the old process remain suspended. If the old process ends the pending request and goes into idle state, the process terminates. If the worker process crashes, or if the request is stopped for other reasons, all pending requests will be assigned to the new process.

Although the ASP.net ISAPI and worker processes are the main components of the ASP.net run-time architecture, there are other executables that also play a role. The following table lists all of these components.

Table 1: Executable files that make up the ASP.net runtime environment
Name Type Account
Aspnet_isapi.dll Win32 DLL (ISAPI extension) local SYSTEM
aspnet_wp.exe Win32 exe ASPNET
Aspnet_filter.dll Win32 DLL (ISAPI filter) Local SYSTEM
Aspnet_state.exe Win32 NT Service ASPNET


The Aspnet_filter.dll component is a small Win32 ISAPI filter used to back up the Cookie-free session state of the ASP.net application. In Windows Server 2003, when the IIS 6 process model is enabled, Aspnet_filter.dll also filters out requests for non-executable resources in the Bin directory.

The role of Aspnet_state.exe is more important to WEB applications because it is used to manage session state. This service is optional and can be used to save session state data outside of the WEB application's memory space. This executable file is an NT service that can run locally or remotely. When the service is activated, you can configure the ASP.net application to save all session information in memory in this process. A similar scenario is to provide a more reliable way of storing data without being affected by process recycling and asp.net application failures. The service runs under the ASPNET local account, but it can be configured with the Service Control Manager interface.

Another executable file that should be introduced is aspnet_regiis.exe, which, although strictly speaking, does not belong to the ASP.NET runtime structure. The utility can be used to configure the environment to execute different versions of ASP.net on a single computer, and to repair IIS and asp.net corrupted configurations. The utility works by updating the script mappings that are stored in the root and subdirectory of the IIS configuration database. Script mapping is an association between resource types and asp.net modules. Finally, you can use the tool to display the status of the installed version of ASP.net and perform other configuration actions, such as granting NTFS permissions to a specific folder, and creating a client script directory.

Web Garden Model

The Web Garden model can be configured by the <processModel> section of the Machine.config file. Note that the <processModel> section is the only configuration section that cannot be placed in an application-specific Web.config file. This means that Web Garden mode can be applied to all applications running on the computer. However, you can adjust your computer's settings for individual applications by using the <location> node in the Machine.config source file.

The <processModel> section has two properties that can affect the Web Garden model, which are webgarden and cpumask. The Webgarden property accepts a Boolean value that indicates whether multiple worker processes are used (one related CPU corresponds to a process). By default, the value of this property is false. The Cpumask property holds a DWORD value that is represented as a bit mask for CPUs capable of running the ASP.net worker process. The default value is-1 (0xFFFFFF), which means that all available CPUs can be used. If the Webgarden property is False, the contents of the Cpumask property are ignored. The Cpumask property also sets an upper bound for the number of copies of the running aspnet_wp.exe.

As the saying goes, "All that glitters is not gold", it is suitable for use here. Web Garden mode enables multiple worker processes to run at the same time. However, it is important to note that all processes have their own application state, in-process session state, ASP.net caching, static data, and other content required to run the application. After Web Garden mode is enabled, ASP.net ISAPI will start the worker process as much as possible based on the number of CPUs, each of which is a complete clone of the next process (each process is closely related to the corresponding CPU). To balance the workload, incoming requests are partitioned between running processes in a single loop. Worker processes are reclaimed as if they were in a single processor. Note that ASP.net inherits all CPU usage restrictions in the operating system and does not include custom semantics for implementation restrictions.

In summary, the WEB Garden model does not apply to all applications. The more state the application has, the more performance it loses. The work data is stored in a block of shared memory so that changes entered by one process can be immediately known to other processes. However, when the request is processed, the work data is copied into the context of the process. As a result, each worker process handles its own work data, and the more state the application has, the greater the performance loss. In view of this, careful and sensible application benchmark testing is absolutely necessary.

Changes made to the <processModel> section of the configuration file will not take effect until IIS is restarted. In IIS 6, the parameters of the Web Garden mode are saved in the IIS metabase, and the Webgarden and Cpumask properties are ignored.

HTTP Pipeline

After the asp.net ISAPI extension starts the worker process, it passes some command-line arguments. The worker process uses these parameters to perform tasks that need to be performed before the CLR is loaded. The values that are passed include the level of authentication required by COM and DCOM security, the number of named pipes that can be used, and the IIS process identity. The name of a named pipe is randomly generated using the IIS process identity and the number of allowable pipes. The worker process does not receive the name of the available pipe, but can receive the information needed to identify the pipe name.

What does COM and DCOM security have to do with the Microsoft. NET Framework? In fact, the CLR is provided as a COM object. More precisely, the CLR itself is not made up of COM code, but the interface to the CLR is a COM object. Therefore, the worker process loads the CLR the same way that the COM object is loaded.

When an ASPX request encounters IIS, the WEB server assigns a token based on the authentication model (anonymous, Windows, Basic, or Digest) that is selected. When a worker process receives a request to be processed, the token is passed to the worker process. The request is fetched by a thread in the worker process. The thread inherits the identity token from the IIS thread that originally fetched the incoming request. In aspnet_wp.exe, the actual account responsible for processing the request depends on how the impersonation is configured in a particular ASP.net application. If the impersonation is disabled (the default setting), the thread will run under the account of the worker process. By default, the account is ASPNET in the ASP.net process model and is NetworkService in the IIS 6 process model. Both accounts are "weak" accounts and provide limited functionality to effectively withstand revert-to-self Attack. (a reply-to attack is the return of a security token from the impersonated client to the parent process token.) Assigning a weak account to a worker process can frustrate this type of attack. )

In a nutshell, one of the main tasks of the ASP.net worker process is to give the request to a series of managed objects called HTTP pipes. To activate an HTTP pipe, you can create a new instance of the HttpRuntime class, and then call its ProcessRequest method. As mentioned earlier, ASP.net always runs only one worker process (unless the Web Garden model is enabled), which manages the Web applications in a separate AppDomain. Each AppDomain has its own instance of the HttpRuntime class, which is the input point in the pipeline. The HttpRuntime object Initializes a series of internal objects that help implement the request. Helper objects include cache Manager (cached object) and internal file System Monitor (used to detect changes to the source files that make up your application). HttpRuntime creates a context for the request and populates the context with the HTTP information associated with the request. The context is represented by an instance of the HttpContext class.

Another Helper object created early in the HTTP run-time settings is a text writer that contains the response text for the browser. The text writer is an instance of the Httpwriter class, which caches text that is sent programmatically by the page code. When the HTTP runtime is initialized, it looks for the application object that implements the request. The Application object is an instance of the HttpApplication class, which is the class behind the Global.asax file. Global.asax is optional when programming, but is required when building a structure. Therefore, if you do not have a build class in your application, you must use the default object. The ASP.net runtime includes several intermediate factory classes that can be used to find and return a valid Handler object to handle the request. The first factory class used throughout the process is httpapplicationfactory. Its primary task is to use URL information to find a matching relationship between a URL virtual directory and a pooled HttpApplication object.

The behavior of the application factory class can be summed up in the following points:

The factory class maintains HttpApplication object pools and uses them to handle application requests. The life of the pool is the same as the life of the application.

When the application's first request arrives, the factory class extracts information about the application type (the Global.asax Class), sets the file to monitor the changes, creates the application state, and triggers the Application_OnStart event.

The factory class obtains a HttpApplication instance from the pool and puts the request to be processed into the instance. If no objects are available, a new HttpApplication object is created. To create a HttpApplication object, you need to finish compiling the Global.asax application file first.

HttpApplication starts processing the request and can only process the new request after the request has been completed. If a new request from the same resource is received, it is handled by other objects in the pool.

The Application object allows all registered HTTP modules to preprocess the request and identify the type of handler that is best suited to handle the request. This is done by looking up the extension of the requested URL and the information in the configuration file.

HTTP handlers are classes that implement the IHttpHandler interface. The. NET Framework provides predefined handlers for common resource types, including ASPX pages and Web services. The
The IHttpHandler interface provides two methods: IsReusable and ProcessRequest. The former returns a Boolean value indicating whether the handler can be pooled. (Most of the predefined handlers are pooled, but you can define the handlers that require a new instance each time.) The ProcessRequest method contains all the logic required to handle a particular type of resource. For example, the handler for an ASPX page is based on the following pseudo code:

private void ProcessRequest ()
{
Determine if the request is a postback (postback)
IsPostBack = DeterminePostBackMode ();

Page_Init event that triggers the ASPX source code
Pageinit ();

Loads the ViewState and processes the sent values.
if (IsPostBack) {
Loadpageviewstate ();
Processpostdata ();
}

Page_Load event that triggers the ASPX source code
Pageload ();

1) to process the sent value again (when
When a control is dynamically created)
2 The server-side event that changes the property is promoted to the input-driven
Control (that is, the state of the check box changes)
3 Execute all the code associated with the postback event
if (IsPostBack) {
Processpostdatasecondtry ();
Raisechangedevents ();
RaisePostBackEvent ();
}

Page_PreRender event that triggers the ASPX source code
PreRender ();

To save the current state of a control to ViewState
Savepageviewstate ();

Renders the page content to HTML
RenderControl (Createhtmltextwriter (response.output));
}

The model based on the HTTP handler is the same regardless of the type of resource being invoked. The only element that changes with the type of the resource is the handler. The HttpApplication object is responsible for finding which handler should be used to process the request. The HttpApplication object is also responsible for detecting changes made to dynamically created assemblies that represent resources, such as. aspx pages or. asmx Web services. If a change is detected, the Application object ensures that the most recent source of the requested resource is compiled and loaded.

Temporary File and page assembly

To fully understand the ASP.net HTTP runtime, let's analyze what happens to the file system layer when you request a ASP.net page. Next, you will learn about a set of dynamically created temporary files that are managed and monitored by objects in the HTTP pipeline.

Although you can isolate the core code of the page to C # or Microsoft behind your code? Visual Basic?. NET classes, but you can write and deploy Web pages as. aspx text files. For pages to be displayed as URLs,. aspx files must always be available in the Web space of the application. The actual content of the. aspx file determines the assembly (or assemblies) to be loaded by the Application object.

By design, the HttpApplication object looks for a class that is named according to the requested ASPX file. If the page is named Sample.aspx, the corresponding class name to be loaded is asp.sample_aspx. The Application object finds such classes in all the assembly folders of the Web application, including the global Assembly Cache (GAC), the Bin subfolder, and the temporary asp.net Files folder. If such a class is not found, the HTTP structure analyzes the source code of the. aspx file, creates a C # or Visual Basic. NET Class (specifically, depending on the language set on the. aspx page), and compiles it. The name of the newly created assembly is randomly generated and is located in an application-specific subfolder, as follows: C:windowsmicrosoft.netframeworkv1.1.4322temporary asp.net Files.

Subfolder v1.1.4322 is specific to ASP.net 1.1. If you are using ASP.net 1.0, the version number of the subfolder will be different, that is, the subfolder name is v1.0.3705. When you access the page again, the assembly already exists and does not need to be recreated. However, how does the HttpApplication object determine whether a page-specific assembly exists? Does it have to scan a large number of folders each time? No, that's not true.

The Application object only looks at the contents of a particular folder in the temporary asp.net Files folder. The specific path (the application-specific path) is returned by the Httpruntime.codegendir property. If you are accessing an. aspx file for the first time (that is, the page assembly has not yet been created), there is no XML file in the folder that begins with the ASPX page name. For example, an sample.aspx page with a dynamic assembly should have the following entry:

Sample.aspx.XXXXX.xml

The XXXXX placeholder is a hash code. By reading the contents of the XML file, the Application object can understand the name of the assembly to load and the class to be fetched. The following code fragment is a typical part of this Helper file. The name of the assembly that contains the Asp.sample_aspx class is MVXVX8XR.

<preserve assem= "MVXVX8XR" type= "asp.sample_aspx"
<FILEDEP name= "c:inetpubwwwrootvdirsample.aspx"/>
</preserve>

Of course, the file is created only when the source code of the Filedep file is parsed to generate a dynamic assembly. Any changes made to the FILEDEP file will invalidate the assembly and must be recompiled on the next request. It is important to note that in future versions of the ASP.net architecture, the implementation process may change significantly. Whatever the reason, you must be very careful as long as you decide to use it in your current application.

When you create a new assembly for a page because of an update, asp.net verifies that the old assembly can be deleted. If the old assembly contains only the modified page's class, asp.net will attempt to delete and replace the assembly, otherwise a new assembly will be created with the old assembly preserved.

During the deletion process, asp.net may find that the assembly file has been loaded and locked. In this case, you can add a "to the old assembly." DELETE extension to rename it. (Note that all Windows files can be renamed during use.) As long as the application restarts (for example, due to changes made to an application file such as Global.asax and Web.config), these temporary. The delete file will be deleted. However, when the next request is processed, the ASP.net runtime does not delete the files.

Note that by default, before the entire application restarts, each ASP.net application can recompile up to 15 pages, while losing some session and application data. When the most recent compilation exceeds the threshold set in the
Summary

The ASP.net application has two major characteristics: the process model and the Page object model. ASP.net uses some of the features of IIS 6.0 in advance, while IIS 6.0 is the new, groundbreaking Microsoft WEB information service available in Windows Server 2003. It is particularly worth mentioning that the ASP.net application that runs in a stand-alone worker process behaves the same as all applications in IIS 6. Also, while runtime exceptions, memory leaks, or program errors can occur, the ASP.net runtime automatically reclaims the worker process to ensure exceptional performance. This functionality has become a system feature of IIS 6.0.

In this article, I outlined the basics of the default ASP.net process model, as well as the interaction between IIS-level code (asp.net ISAPI extension) and worker processes. The latest differences with the IIS 6 process model are also described.



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.