Asp.net|session
The simplicity of the design and the high efficiency of a stateless connection are important reasons why HTTP protocols can be so successful. In order to achieve a balance between stateless HTTP requests and stateful client operations, the concept of server-side sessions (session) is generated. After the client connects to the server, the WEB server generates and maintains a client's session, and when the client connects to the server again through a stateless HTTP protocol, the server associates the client to a session based on a credential submitted by the client, such as a Cookie or URL parameter. This approach is widely used in a variety of development languages and development environments.
In ASP.net, Web applications and session states are maintained separately, separating the functionality of Web application sessions through HttpApplication and HttpSessionState. The application layer logic is implemented in the Global.asax file, the runtime is compiled into an System.Web.HttpApplication instance, and the session is a separate System.Web.SessionState.HttpSessionState instance, which is maintained by the server for each user session, and is accessed through a asp.net page compiled into a System.Web.UI.Page object subclass. About the different levels of the relationship in ASP.net can refer to my previous article ". NET 1.1 Precompiled ASP.net page Implementation principle analysis [1] automatic precompilation mechanism analysis", hereinafter referred to as "Wen 1".
asp.net when processing a client request, first generates a System.Web.HttpContext object based on the client environment and passes this object as the execution context to the subsequent page execution code.
In the analysis of "Wen 1", we can see that HttpRuntime constructs the HttpContext object based on the environment given in HttpWorkerRequest, and obtains the available application from the application pool with the secondary object as a parameter, before processing the page request. The brief code is as follows:
The following are program code:
private void Httpruntime.processrequestinternal (HttpWorkerRequest wr)
{
Constructing an HTTP call context object
HttpContext ctxt = new HttpContext (WR, 0);
//...
Get the current WEB application instance
IHttpHandler handler = httpapplicationfactory.getapplicationinstance (Ctxt);
Call handler actually process page requests
}
The HttpApplicationFactory factory maintains an available application instance buffer pool, and the user lowers the load on the Application object constructs.
If no instance of the Application object is available in the pool, the object factory will eventually call the System.Web.HttpRuntime.CreateNonPublicInstance method to construct a new application instance and invoke its Initinternal method initialization. Detailed step analysis See "Wen 1"
The following are program code:
Internal static IHttpHandler Httpapplicationfactory.getapplicationinstance (HttpContext ctxt)
{
Working with custom applications
//...
Handling Debugging Requests
//...
Determines whether the current HttpApplicationFactory instance needs to be initialized
//...
Getting a WEB application instance
Return httpapplicationfactory._theapplicationfactory.getnormalapplicationinstance (Ctxt);
}
Private HttpApplication Httpapplicationfactory.getnormalapplicationinstance (HttpContext context)
{
HttpApplication app = null;
Attempt to get from the cast of a WEB application instance queue
//...
if (app = null)
{
Constructing a new instance of a WEB application
App = (HttpApplication) System.Web.HttpRuntime.CreateNonPublicInstance (This._theapplicationtype);
Initializing a WEB application instance
App. Initinternal (context, this._state, this._eventhandlermethods);
}
return app;
}
The System.Web.HttpApplication.InitInternal function here completes initialization of the application object, including invoking the Httpapplication.initmodules function to initialize the HTTP Module (described later in detail) and saves the HttpContext instance passed in as a parameter to the Httpapplication._context field. This HTTP context object is later used to get the session object.
The following are program code:
public class HttpApplication: ...
{
Private HttpContext _context;
Private HttpSessionState _session;
Public HttpSessionState Session
{
Get
{
HttpSessionState state = null;
if (this._session!= null)
{
state = This._session;
}
else if (this._context!= null)
{
state = This._context. session;
}
if (state = null)
{
Throw New HttpException (httpruntime.formatresourcestring ("session_not_available");
}
return state;
}
}
}
The way to get a session in a ASP.net page is similar, and it's done through HttpContext.
The following are program code:
public class Page: ...
{
Private HttpSessionState _session;
private bool _sessionretrieved;
Public virtual HttpSessionState Session
{
Get
{
if (!this._sessionretrieved)
{
This._sessionretrieved = true;
Try
{
This._session = this. Context.session;
}
catch (Exception)
{
}
}
if (this._session = null)
{
Throw New HttpException (httpruntime.formatresourcestring ("session_not_enabled");
}
return this._session;
}
}
}
In HttpContext, you actually save information such as session objects through a hash table.
The following are program code:
Public sealed class HttpContext: ...
{
Private Hashtable _items;
Public IDictionary Items
{
Get
{
if (This._items = null)
{
This._items = new Hashtable ();
}
return this._items;
}
}
Public HttpSessionState Session
{
Get
{
Return ((HttpSessionState) this. items["Aspsession"]);
}
}
}
And where did the httpcontext.session visit come from? This again needs to go back to the Httpapplication.initmodules function we mentioned earlier.
Machine.config in the. NET installation directory Config subdirectory defines global configuration information, and HttpApplication is initialized using the configuration information in the System.Web section of the.
The following are program code:
<system.web>
<add name= "OutputCache" type= "System.Web.Caching.OutputCacheModule"
<add name= "Session" Type= "System.Web.SessionState.SessionStateModule"/>
<add name= "windowsauthentication" type= "System.Web.Security.WindowsAuthenticationModule"
<add name= "FormsAuthentication" type= "System.Web.Security.FormsAuthenticationModule"
<add name= "passportauthentication" type= "System.Web.Security.PassportAuthenticationModule"
<add name= "urlauthorization" type= "System.Web.Security.UrlAuthorizationModule"
<add name= "fileauthorization" type= "System.Web.Security.FileAuthorizationModule"
<add name= "Errorhandlermodule" type= "System.Web.Mobile.ErrorHandlerModule, System.Web.Mobile, version=1.0.5000.0, Culture=neutral, publickeytoken=b03f5f7f11d50a3a "/>
</system.web>
The httpmodules node specifies the list of modules that the HttpApplication needs to initialize, and the Httpapplication.initmodules function mentioned earlier is officially initialized based on this list
The following are program code:
private void Httpapplication.initmodules ()
{
Httpmodulesconfiguration cfgmodules = (httpmodulesconfiguration) httpcontext.getappconfig ("System.web/httpModules ");
if (cfgmodules = null)
{
Throw New HttpException (httpruntime.formatresourcestring ("Missing_modules_config");
}
_modulecollection = Cfgmodules.createmodules ();
for (int i = 0; I _modulecollection.count i++)
{
_modulecollection[i]. Init (this);
}
Globalizationconfig Cfgglobal = (globalizationconfig) httpcontext.getappconfig ("System.web/globalization");
if (Cfgglobal!= null)
{
_applevelculture = cfgglobal.culture;
_appleveluiculture = cfgglobal.uiculture;
}
}
The System.Web.SessionState.SessionStateModule object for the session node is constructed by the Httpmodulesconfiguration.createmodules method and calls its Init Function initialization. The SessionStateModule class is actually responsible for managing and creating the session, and the user can create a class that implements the IHttpModule interface entirely, implementing the control of the session, such as implementing a state synchronization that supports clustering, and so on.
The Sessionstatemodule.init method is mainly responsible for the SES in the Machine.config file