Sunday 27 October 2013

ASP.NET Page Life Cycle

 

ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0

Stage

Description

User requests an application resource from the Web server.

The life cycle of an ASP.NET application starts with a request sent by a browser to the Web server (for ASP.NET applications, typically IIS). ASP.NET is an ISAPI extension under the Web server. When a Web server receives a request, it examines the file-name extension of the requested file, determines which ISAPI extension should handle the request, and then passes the request to the appropriate ISAPI extension. ASP.NET handles file name extensions that have been mapped to it, such as .aspx, .ascx, .ashx, and .asmx.

clip_image001Note

If a file name extension has not been mapped to ASP.NET, ASP.NET will not receive the request. This is important to understand for applications that use ASP.NET authentication. For example, because .htm files are typically not mapped to ASP.NET, ASP.NET will not perform authentication or authorization checks on requests for .htm files. Therefore, even if a file contains only static content, if you want ASP.NET to check authentication, create the file using a file name extension mapped to ASP.NET, such as .aspx.

clip_image001[1]Note

If you create a custom handler to service a particular file name extension, you must map the extension to ASP.NET in IIS and also register the handler in your application's Web.config file. For more information, see HTTP Handlers and HTTP Modules Overview.

ASP.NET receives the first request for the application.

When ASP.NET receives the first request for any resource in an application, a class named ApplicationManager creates an application domain. Application domains provide isolation between applications for global variables and allow each application to be unloaded separately. Within an application domain, an instance of the class named HostingEnvironment is created, which provides access to information about the application such as the name of the folder where the application is stored.

The following diagram illustrates this relationship:

clip_image003

ASP.NET also compiles the top-level items in the application if required, including application code in the App_Code folder. For more information, see "Compilation Life Cycle" later in this topic.

ASP.NET core objects are created for each request.

After the application domain has been created and the HostingEnvironment object instantiated, ASP.NET creates and initializes core objects such as HttpContext, HttpRequest, and HttpResponse. The HttpContext class contains objects that are specific to the current application request, such as the HttpRequest and HttpResponse objects. The HttpRequest object contains information about the current request, including cookies and browser information. The HttpResponse object contains the response that is sent to the client, including all rendered output and cookies.

An HttpApplication object is assigned to the request

After all core application objects have been initialized, the application is started by creating an instance of the HttpApplication class. If the application has a Global.asax file, ASP.NET instead creates an instance of the Global.asax class that is derived from the HttpApplication class and uses the derived class to represent the application.

clip_image001[2]Note

The first time an ASP.NET page or process is requested in an application, a new instance of HttpApplication is created. However, to maximize performance, HttpApplication instances might be reused for multiple requests.

When an instance of HttpApplication is created, any configured modules are also created. For instance, if the application is configured to do so, ASP.NET creates a SessionStateModule module. After all configured modules are created, the HttpApplication class's Init method is called.

The following diagram illustrates this relationship:

clip_image005

The request is processed by the HttpApplication pipeline.

The following events are executed by the HttpApplication class while the request is processed. The events are of particular interest to developers who want to extend the HttpApplication class.

 

When the first request is made to an application, ASP.NET compiles application items in a specific order. The first items to be compiled are referred to as the top-level items. After the first request, the top-level items are recompiled only if a dependency changes. The following table describes the order in which ASP.NET top-level items are compiled.

Item

Description

App_GlobalResources

The application's global resources are compiled and a resource assembly is built. Any assemblies in the application's Bin folder are linked to the resource assembly.

App_WebResources

Proxy types for Web services are created and compiled. The resulting Web references assembly is linked to the resource assembly if it exists.

Profile properties defined in the Web.config file

If profile properties are defined in the application's Web.config file, an assembly is generated that contains a profile object.

App_Code

Source code files are built and one or more assemblies are created. All code assemblies and the profile assembly are linked to the resources and Web references assemblies if any.

Global.asax

The application object is compiled and linked to all of the previously generated assemblies.

After the application's top level items have been compiled, ASP.NET compiles folders, pages, and other items as needed. The following table describes the order in which ASP.NET folders and items are compiled.

Item

Description

App_LocalResources

If the folder containing the requested item contains an App_LocalResources folder, the contents of the local resources folder are compiled and linked to the global resources assembly.

Individual Web pages (.aspx files), user controls (.ascx files), HTTP handlers (.ashx files), and HTTP modules (.asmx files)

Compiled as needed and linked to the local resources assembly and the top-level assemblies.

Themes, master pages, other source files

Skin files for individual themes, master pages, and other source code files referenced by pages are compiled when the referencing page is compiled.

Compiled assemblies are cached on the server and reused on subsequent requests and are preserved across application restarts as long as the source code is unchanged.

Because the application is compiled on the first request, the initial request to an application can take significantly longer than subsequent requests. You can precompile your application to reduce the time required for the first request. For more information, see How to: Precompile ASP.NET Web Site Projects.

 

 

 

ASP.NET Application Life Cycle Overview for IIS 7.0

 

A request in IIS 7.0 Integrated mode passes through stages that are like the stages of requests for ASP.NET resources in IIS 6.0. However, in IIS 7.0, these stages include several additional application events, such as the MapRequestHandler, LogRequest, and PostLogRequest events.

The main difference in processing stages between IIS 7.0 and IIS 6.0 is in how ASP.NET is integrated with the IIS server. In IIS 6.0, there are two request processing pipelines. One pipeline is for native-code ISAPI filters and extension components. The other pipeline is for managed-code application components such as ASP.NET. In IIS 7.0, the ASP.NET runtime is integrated with the Web server so that there is one unified request processing pipeline for all requests. For ASP.NET developers, the benefits of the integrated pipeline are as follows:

· The integrated pipeline raises all the events that are exposed by the HttpApplication object, which enables existing ASP.NET HTTP modules to work in IIS 7.0 Integrated mode.

· Both native-code and managed-code modules can be configured at the Web server, Web site, or Web application level. This includes the built-in ASP.NET managed-code modules for session state, forms authentication, profiles, and role management. Furthermore, managed-code modules can be enabled or disabled for all requests, regardless of whether the request is for an ASP.NET resource like an .aspx file.

· Managed-code modules can be invoked at any stage in the pipeline. This includes before any server processing occurs for the request, after all server processing has occurred, or anywhere in between.

· You can register and enable or disable modules through an application’s Web.config file.

The following illustration shows the configuration of an application's request pipeline. The example includes the following:

· The Anonymous native-code module and the Forms managed-code module (which corresponds to FormsAuthenticationModule). These modules are configured, and they are invoked during the Authentication stage of the request.

· The Basic native-code module and the Windows managed-code module (which corresponds to WindowsAuthenticationModule). They are shown, but they are not configured for the application.

· The Execute handler stage, where the handler (a module scoped to a URL) is invoked to construct the response. For .aspx files, the PageHandlerFactory handler is used to respond to the request. For static files, the native-code StaticFileModule module responds to the request.

· The Trace native-code module. This is shown, but it is not configured for the application.

· The Custom module managed-code class. It is invoked during the Log request stage.

clip_image002

For information about known compatibility issues with ASP.NET applications that are being migrated from earlier versions of IIS to IIS 7.0, see the "Known Differences Between Integrated Mode and Classic Mode" section of Upgrading ASP.NET Applications to IIS 7.0: Differences between IIS 7.0 Integrated Mode and Classic mode.

clip_image003Life Cycle Stages


The following table lists the stages of the ASP.NET application life cycle with Integrated mode in IIS 7.0.

Stage

Description

A request is made for an application resource.

The life cycle of an ASP.NET application starts with a request sent by a browser to the Web server.

In Classic mode in IIS 7.0 and in IIS 6.0, the ASP.NET request pipeline is separate from the Web server pipeline. Modules apply only to requests that are routed to the ASP.NET ISAPI extension. If the file-name extension of the requested resource type is not explicitly mapped to ASP.NET, ASP.NET functionality is not invoked for the request because the request is not processed by the ASP.NET runtime.

In integrated mode in IIS 7.0, a unified pipeline handles all requests. When the integrated pipeline receives a request, the request passes through stages that are common to all requests. These stages are represented by the RequestNotification enumeration. All requests can be configured to take advantage of ASP.NET functionality, because that functionality is encapsulated in managed-code modules that have access to the request pipeline. For example, even though the .htm file-name extension is not explicitly mapped to ASP.NET, a request for an HTML page still invokes ASP.NET modules. This enables you to take advantage of ASP.NET authentication and authorization for all resources.

The unified pipeline receives the first request for the application.

When the unified pipeline receives the first request for any resource in an application, an instance of the ApplicationManager class is created, which is the application domain that the request is processed in. Application domains provide isolation between applications for global variables and enable each application to be unloaded separately. In the application domain, an instance of the HostingEnvironment class is created, which provides access to information about the application, such as the name of the folder where the application is stored.

During the first request, top-level items in the application are compiled if required, which includes application code in the App_Code folder. You can include custom modules and handlers in the App_Code folder as described in Managed-code Modules in IIS 7.0 later in this topic.

Response objects are created for each request.

After the application domain has been created and the HostingEnvironment object has been instantiated, application objects such as HttpContext, HttpRequest, and HttpResponse are created and initialized. The HttpContext class contains objects that are specific to the current application request, such as the HttpRequest and HttpResponse objects. The HttpRequest object contains information about the current request, which includes cookies and browser information. The HttpResponse object contains the response that is sent to the client, which includes all the rendered output and cookies.

The following are some key differences between IIS 6.0 and IIS 7.0 running in Integrated mode and with the .NET Framework 3.0 or later:

· The SubStatusCode property of the HttpResponse object is available for setting codes that are useful for failed-request tracing. For more information, see Troubleshooting Failed Requests Using Failed Request Tracing in IIS 7.0.

· The Headers property of the HttpResponse object provides access to response headers for the response.

· Two properties of the HttpContext object, IsPostNotification and CurrentNotification, are used when one event handler handles several HttpApplication events.

· The Headers and ServerVariables property of the HttpRequest object are write-enabled.

An HttpApplication object is assigned to the request

After all application objects have been initialized, the application is started by creating an instance of the HttpApplication class. If the application has a Global.asax file, ASP.NET instead creates an instance of the Global.asax class that is derived from the HttpApplication class. It then uses the derived class to represent the application.

clip_image003[1]Note

The first time that an ASP.NET page or process is requested in an application, a new instance of the HttpApplication class is created. However, to maximize performance, HttpApplication instances might be reused for multiple requests.

Which ASP.NET modules are loaded (such as the SessionStateModule) depends on the managed-code modules that the application inherits from a parent application. It also depends on which modules are configured in the configuration section of the application's Web.config file. Modules are added or removed in the application's Web.config modules element in the system.webServer section. For more information, see How to: Configure the <system.webServer> Section for IIS 7.0.

The request is processed by the HttpApplication pipeline.

The following tasks are performed by the HttpApplication class while the request is being processed. The events are useful for page developers who want to run code when key request pipeline events are raised. They are also useful if you are developing a custom module and you want the module to be invoked for all requests to the pipeline. Custom modules implement the IHttpModule interface. In Integrated mode in IIS 7.0, you must register event handlers in a module's Init method.

1. Validate the request, which examines the information sent by the browser and determines whether it contains potentially malicious markup. For more information, see ValidateRequest and Script Exploits Overview.

2. Perform URL mapping, if any URLs have been configured in the UrlMappingsSection section of the Web.config file.

3. Raise the BeginRequest event.

4. Raise the AuthenticateRequest event.

5. Raise the PostAuthenticateRequest event.

6. Raise the AuthorizeRequest event.

7. Raise the PostAuthorizeRequest event.

8. Raise the ResolveRequestCache event.

9. Raise the PostResolveRequestCache event.

10. Raise the MapRequestHandler event. An appropriate handler is selected based on the file-name extension of the requested resource. The handler can be a native-code module such as the IIS 7.0 StaticFileModule or a managed-code module such as the PageHandlerFactory class (which handles .aspx files).

11. Raise the PostMapRequestHandler event.

12. Raise the AcquireRequestState event.

13. Raise the PostAcquireRequestState event.

14. Raise the PreRequestHandlerExecute event.

15. Call the ProcessRequest method (or the asynchronous version IHttpAsyncHandler.BeginProcessRequest) of the appropriate IHttpHandler class for the request. For example, if the request is for a page, the current page instance handles the request.

16. Raise the PostRequestHandlerExecute event.

17. Raise the ReleaseRequestState event.

18. Raise the PostReleaseRequestState event.

19. Perform response filtering if the Filter property is defined.

20. Raise the UpdateRequestCache event.

21. Raise the PostUpdateRequestCache event.

22. Raise the LogRequest event.

23. Raise the PostLogRequest event.

24. Raise the EndRequest event.

25. Raise the PreSendRequestHeaders event.

26. Raise the PreSendRequestContent event.

 

 

 

 

 

Page life cycle in IIS Integrated mode

Ex:

 

In Integrated mode, the ASP.NET request-processing stages that are exposed to modules are directly connected to the corresponding stages of the IIS 7 pipeline. The complete pipeline contains the following stages, which are exposed as HttpApplication events in ASP.NET:

1. BeginRequest. The request processing starts.

2. AuthenticateRequest. The request is authenticated. IIS 7 and ASP.NET authentication modules subscribe to this stage to perform authentication.

3. PostAuthenticateRequest.

4. AuthorizeRequest. The request is authorized. IIS 7 and ASP.NET authorization modules check whether the authenticated user has access to the resource requested.

5. PostAuthorizeRequest.

6. ResolveRequestCache. Cache modules check whether the response to this request exists in the cache, and return it instead of proceeding with the rest of the execution path. Both ASP.NET Output Cache and IIS 7 Output Cache features execute.

7. PostResolveRequestCache.

8. MapRequestHandler. This stage is internal in ASP.NET and is used to determine the request handler.

9. PostMapRequestHandler.

10. AcquireRequestState. The state necessary for the request execution is retrieved. ASP.NET Session State and Profile modules obtain their data.

11. PostAcquireRequestState.

12. PreExecuteRequestHandler. Any tasks before the execution of the handler are performed.

13. ExecuteRequestHandler. The request handler executes. ASPX pages, ASP pages, CGI programs, and static files are served.

14. PostExecuteRequestHandler

15. ReleaseRequestState. The request state changes are saved, and the state is cleaned up here. ASP.NET Session State and Profile modules use this stage for cleanup.

16. PostReleaseRequestState.

17. UpdateRequestCache. The response is stored in the cache for future use. The ASP.NET Output Cache and IIS 7 Output Cache modules execute to save the response to their caches.

18. PostUpdateRequestCache.

19. LogRequest. This stage logs the results of the request, and is guaranteed to execute even if errors occur.

20. PostLogRequest.

21. EndRequest. This stage performs any final request cleanup, and is guaranteed to execute even if errors occur.

By using the familiar ASP.NET APIs, the ability to execute in the same stages as IIS 7 modules makes tasks that were only previously accessible in native ISAPI filters and extensions now possible in managed code.

For example, you can now write modules that do the following:

1. Intercept the request before any processing has taken place, for example rewriting URLs or performing security filtering.

2. Replace built-in authentication modes.

3. Modify the incoming request contents, such as request headers.

4. Filter outgoing responses for all content types.

See Developing an IIS 7 Module with .NET for a good example of how to extend IIS 7 with a custom ASP.NET authentication module.

Expanded ASP.NET APIs

The ASP.NET APIs remain backward compatible with previous releases, which allows existing modules to work in IIS 7 without modification, and to apply to all application content without code changes.

However, modules that are written for IIS 7 Integrated mode can take advantage of a few additional APIs to enable key request-processing scenarios that were not previously available.

The new HttpResponse.Headers collection allows modules to inspect and manipulate response headers that other application components generate. For example, you can change the Content-Type header that is generated by an ASP page to prompt a download dialog box in the browser. The Cookies collection on the HttpResponse class is also enhanced to allow modification of cookies that are generated as part of the request processing, even if they were created outside of ASP.NET.

The HttpRequest.Headers collection is write-enabled, which allows modules to manipulate the incoming request headers. Use this to change the behavior of other server components – for example, you can force a localized application to respond to the client in a different language by dynamically changing the value of the Accept-Language header.

Finally, the HttpRequest.ServerVariables collection is now writeable, which allows IIS 7 server variables to be set. ASP.NET modules use this functionality to change values that are provided by IIS 7, and to create new server variables that are visible to other application frameworks, like PHP.

Runtime Integration

In addition to the new APIs, Integrated mode enables existing ASP.NET functionality to provide more value to your application.

The tracing facilities that are provided by ASP.NET, including the System.Diagnostics.Trace class and the ASP.NET page tracing feature, now emit trace information into the IIS 7 trace system. This enables the trace information that is generated during request processing by both IIS 7 and ASP.NET components to be placed in a single log file, facilitating better diagnostics of server issues.

The ASP.NET response-filtering feature, which allows responses to be changed by using a Stream interface before it goes to the client, is enhanced to allow filtering of non-ASP.NET content. Therefore, you can use ASP.NET filtering on all server content, or selectively install the filter only for requests to content that you want to process. With this capability, you can write filtering features that inject or censor certain content in the site's responses, regardless of whether this content comes from an ASPX page or a static file.

 

image

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Blogger Labels: Page,Life,Cycle,Application,Overview,Stage,Description,User,resource,server,ISAPI,extension,extensions,Note,authentication,example,authorization,custom,handler,information,Handlers,Modules,ApplicationManager,domain,domains,isolation,Within,instance,HostingEnvironment,folder,diagram,relationship,items,App_Code,Compilation,topic,HttpContext,HttpRequest,HttpResponse,response,client,output,HttpApplication,Global,performance,instances,SessionStateModule,module,Init,method,pipeline,events,developers,dependency,Item,App_GlobalResources,resources,assemblies,App_WebResources,Proxy,references,Profile,properties,Source,folders,App_LocalResources,Individual,Themes,Skin,Precompile,Site,Projects,mode,MapRequestHandler,LogRequest,PostLogRequest,difference,pipelines,components,Both,session,role,management,illustration,configuration,Anonymous,Forms,FormsAuthenticationModule,Basic,Windows,WindowsAuthenticationModule,Execute,PageHandlerFactory,StaticFileModule,Trace,versions,Known,Differences,Classic,Applications,Stages,RequestNotification,enumeration,advantage,HTML,Framework,SubStatusCode,Requests,Request,Headers,IsPostNotification,CurrentNotification,event,ServerVariables,system,Configure,Section,tasks,IHttpModule,interface,Validate,ValidateRequest,Script,Exploits,Perform,URLs,UrlMappingsSection,Raise,BeginRequest,AuthenticateRequest,PostAuthenticateRequest,AuthorizeRequest,PostAuthorizeRequest,ResolveRequestCache,PostResolveRequestCache,PostMapRequestHandler,AcquireRequestState,PostAcquireRequestState,PreRequestHandlerExecute,Call,ProcessRequest,version,IHttpAsyncHandler,BeginProcessRequest,IHttpHandler,PostRequestHandlerExecute,ReleaseRequestState,PostReleaseRequestState,Filter,UpdateRequestCache,PostUpdateRequestCache,EndRequest,PreSendRequestHeaders,PreSendRequestContent,Cache,execution,path,State,data,PreExecuteRequestHandler,ExecuteRequestHandler,ASPX,PostExecuteRequestHandler,cleanup,errors,APIs,Intercept,Replace,modes,Modify,responses,modification,scenarios,collection,Content,Type,header,dialog,Cookies,Accept,Language,frameworks,Runtime,Integration,addition,facilities,Diagnostics,Stream,browser,ascx,ashx,asmx,config,variables,asax,whether,webServer

1 comment:

  1. Thanks for sharing valuable information. Your blogs were helpful to

    Dot NET learners. I request to update the blog through step-by-step.

    Also, find the Dot net news at Dot NET Online Training

    ReplyDelete