ASP.NET Life Cycle

The ASP.NET platform defines two important life cycles. The first is the application life cycle, tracks the life of a web application from the moment it starts to the moment it is terminated. The second is request life cycle, defines the path that an HTTP request follows as it moves throught ASP.NET platform from the point at which the initial request is received until the response is sent. 

 

1. Application life cycle

The life cycle of an ASP.NET application begins the moment the application is started and continues while HTTP requests are received from the clients. And the life cycle ends when the application is stopped. 

ASP.NET platform provides notifications of the two stages of life cycle through methods defined by the global.ascx.cs file. 

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }

The default global class is called MvcApplication and derived from System.Web.HttpApplication. 

 

1.1 receiving notifications when application starts and ends

The global class supports two special methods that define the start and end of the application lifecycle. 

Application_Start() Called when the application is started
Application_End() Called when the application is about to terminated

 

The application_start methods is called when the application is first started and provides an opportunity to perform once-off configuration tasks, such as set up areas and routes. The application_end method is called just before the application is terminated and is an opportunity to release any resources. 

Both methods are not defined by the base for the global class, rather asp.net framework uses reflection to look for the methods by name. 

 

2. Request life cycle

The request life cycle is described by a series of events that describe the progress of a request from when it is received through until the response is sent. 

BeginRequest                                                                                           This is triggered as the first event when a new request is received

AuthenticateRequest

PostAuthenticateRequest

The AuthenticateRequest is triggered to identity the user who has made the request. When all of the event handlers have been processed, PostAuthenticateRequest is triggered
AuthorizeRequest   AuthorizeRequest is triggered to authorize the request. When all of the event handles have been processed, PostAuthorizeRequest is triggered.

ResolveRequestCache

PostResolveRequestCache

ResolveRequestCache is triggered to resolve the request from cached data. 

MapRequestHandler

PostMapRequestHandler

MapRequestHandler is triggered when the ASP.NET framework wants to locate a handler for the request. 

AcquireRequestState

PostAcquireRequestState

AcquireRequestState is triggered to obtain the state data associated with the request (such as session data)

PreRequestHandlerExecute

PostRequestHandlerExecute

These events are triggered immediately before and immediately after the hanlder is asked to process the request.

ReleaseRequestState

PostReleaseRequestState

ReleaseRequestState is triggered when the state data associated with the request is no longer required for request processing.
UpdateRequestCache    

LogRequest

PostLogRequest

This event is triggered to provide an opporunity for details of the request to be logged.
EndRequest   This event is triggered just before the HTTP headers are sent to browser

PreSendRequestHeaders

PreSendRequestContent

This event is triggered after the headers have been sent but before the content is sent to browser
Error   This event is triggered when an error is encountered.

You are free to trigger these events through the processing life cycle. You can handle these events in the global application class, in a module, or in a handler. 

 

3. Understanding modules and hanlders

You can respond to request life cycle events directly in the global application class, but it is only situable for simplest of interactions with request. The ASP.NET framework deals with this by supporting modules, which are self-contained class that receive lifecycle events and can monitor and manipulate request. Also, ASP.NEt supports a component called handler, which is responsible for generating a response for a request. The hanlder in MVC framework is responsible for locating a controller and action method to service a request and rendering view. 

Note that the global application class is instantiated by both application and request life cycle. Not only does the asp.net framework create multiple instances to service parallel request, but it also creates separate instances to support each life cycle. 

 

4. Handling Request life cycle events using special methods

To handle these events in the global application class, you create a method with a name that starts with Application_, followed by the event name, such as Application_BeginRequest.

        protected void Application_BeginRequest()
        {
            RecordEvent("BeginRequest");
        }

        protected void Application_AuthenticateRequest()
        {
            RecordEvent("authenticate request");
        }

        protected void Application_PostAuthenticateRequest()
        {
            RecordEvent("Post authenticate request");
        }

 

These events will be called when the BeginRequest, AuthenticateRequest, and PostAuthenticateRequest events are triggered. The ASP.NET framework will invoke these methods automatically. 

4.1 Handling request life-cycle without special method

HttpApplication class defines regular C# events that can be used instead of special methods. 

        public MvcApplication()
        {
            BeginRequest += (sender, args) => RecordEvent("BeginRequest");
            AuthenticateRequest += (sender, args) => RecordEvent("AuthenticateREquest");
            PostAuthenticateRequest += (sender, args) => RecordEvent("PostAuthenticateRequest");
        }

 

4.2 Using single method to handle multiple events

You can use two properties defined by the System.Web.HttpContext class if you want to use a single method to handle multiple life-cycle events without relying onlambda expressions. HttpContext provides details of the current request and the state of the application. 

CurrentNotification                           Indicates the current application event using a value from the System.Web.RequestNotification enumeration
IsPostNotification returns true if the current application event is Post<Name> variant of the event returned by the CurrentNotification property

 

        private void RecordEvent(object src, EventArgs args)
        {
            var eventList = Application["events"] as List<string>;
            if (eventList == null)
            {
                Application["events"] = eventList = new List<string>();
            }

            string name = Context.CurrentNotification.ToString();
            if (Context.IsPostNotification)
            {
                name = "Post" + name;
            }

            eventList.Add(name);
        }

 

5. ASP.NET Context objects

ASP.NET provides a set of objects that are used to provide context information about the current request, response and web application itself. The core class is System.Web.HttpContext. It is universally available throughout the ASP.NET framework and the MVC framework. The important properties are as following:

 

Application                                                               returns the HttpApplicationState object used to manage application state data.
ApplicationInstance returns the HttpApplication object associated with current request
Cache return a cache object used to cache data.
Current (static) returns the HttpContext object for the current request
CurrentHandler returns the IHttpHanlder instance that will generate content for the request. 
IsDebuggingEnabled return true if the debugger is attached to the asp.net application.
Items returns a collection that can be used to pass state data between asp.net framework components that participate in processing a request
GetSection(name) gets the specified configuration section from web.config file
Request   returns an HttpRequest object that provides details of the request being processed
Response returns an HttpResponse object that provides details of the response that is being constructed and that will be sent to the browser. 
Session returns an HttpSession state object that provides access to the session state. Will be null until the PostAcquireRequestState application event has been triggered. 
Server returns HttpServerUtility object that can contain utility functions. 
Timestamp returns a DateTime object that contains the time at which the HttpContext object was created
Trace Used to record diagnostic information

The HttpContext is available through:

Controller                                                     use the HttpContext property defined by Controller, which is the base class for MVC framework
View use the Context property defined by WebViewPage, which is the base class used to compile RazorView
Global Application class Use the context convenience property defined by the HttpApplication class
Module The Init method is passed an HttpContext object when it is invoked, and the life-cycle event handlers are handlers are passed an HttpApplication object, which define a Context property.
Handler The processRequest method is passed an HttpContext object
Univesally You can always get HttpContext object associated with the current request through the static HttpContext.Current property

 

If the model needs information about a request, then obtain this information from the context objects in the controller and pass it as method arguments. 

 

5.1 working with HttpApplication object

HttpApplication is the base class for the global application class. 

Application                                        Maps to HttpContext.Application property, provides access to application-wide state data
CompleteRequest() abandons the life cycle for the currernt request and moves directly to the LogRequest event
Context return HttpContext object
Init() Called when the Init method has been called on each of the registered modules
Modules returns an HttpModuleCollection object that details the modules in the application
RegisterModule(type) Static method that registers a new module
Request returns HttpContext.Request
Response     returns HttpContext.Response
Server Maps to the HttpContext.Server
Session returns the HttpContext.Session value

The request, response, session and User properties all return values of the corresponding properties from the HttpContext, but it will throws an HttpException if the value they get from HttpContext is null. This happens because the HttpApplication class receives notifications for two different life cycle: the application life cycle and the request life cycle. 

 

5.2 working with HttpRequest objects

HttpRequest object describes a single HTTP request as it is being processed. 

AcceptTypes returns a string array containing the MIME types accepted by the browser
Browser returns an HttpBrowserCapabilities object that describes the capabilities of the browser
ContentEncoding return a System.Text.Encoding object represents the character set used to encode the request data
ContentLength                                               returns the number of bytes of content in the request
ContentType return the MIME type of the content
CurrentExecutionFilePathExtension returns the file extension component of the request URL
Headers return a collection containing the request headers
HttpMethod return http method used to make the request(get, post)
InputStream return a stream that can be used to read the contents of the request
IsLocal return true when the request has originated from local machine
MapPath(path) translates a file name within the project to an absolute path
RawUrl   return the part of URL that follows the hostname. 
RequestContext return a requestContext object that provides access to the routing information for a request. 
Url     return the request URL as system.Uri object
UrlReferrer return the referrer URL as system.Uri object
UserAgent return the user-agent string supplied by the browser
UserHostAddress return IP address of the remote client, expressed as string
UserHostName return the DNS name of the remote client
UserLanguage return a string array of the languages prefered by the browser/user

 

You can obtain HttpRequest:\

Controller Request convenience property
View Request convenience property
Global application class Request convenience property
Module HttpContext.Request
Handler HttpContext.Request
Universally HttpContext.Current.Request

Additional properties in HttpRequest:

Files returns a collection of files sent by the browser in a form
Form provides access to the row form data
Params a collection of the combined data items from the querystirng, form fileds, and cookies.  Request["myname"] is the same as Request.Params["myname"]
QueryString return a collection of the query string parameters. 

 

5.3 Working with HttpResponse objects

It provides methods and properties that let you customize the response. 

AppendHeader(name, val) Convenience method to add a new header to the response
BufferOutput Gets or Sets a value indicating whether the request should be buffered completely before it is sent to the browser. The default value is true. 
Cache return httpCachePolicy object that specifies the caching policy for the response. 
CacheControl gets or sets the cache-control HttpHeader for the response
Charset gets or sets the character set specified for the reponse
Clear() remove any content from the response
ClearHeaders() remove all headers from the response
ContentEncoding gets or sets the encoding used for content in the reponse
Headers returns the collection of headers for the reponse
IsClientConnected return true if the client is still connected to the server
IsRequestBeingDirected return true if the browser will be sent a redirection
output   returns a TextWriter that can be used to write text to the reponse
OutputStream returns a Stream that can be used to write binary data to the response.
RedirectLocation gets or sets the value of the HTTP Location header.
Status gets or sets the status for the response, defaut is 200 (OK)
StatusCode gets or sets status code number (200)
StatusDescription gets or sets the text part of status 
SuppressContent

When set to true, this property prevents the response content from being sent to the client. 

Write(data) Writes data to the response output stream
WriteFile(path) Writes the contents of the specified file to output stream. 
   
posted @ 2015-06-24 00:33  tim_bo  阅读(528)  评论(0编辑  收藏  举报