ASP.Net Session

 

SESSION

What is Session:
Session is an object at server side which helps in implementing the mechanism to identify a revisiting user over a stateless protocol like HTTP.

What is Session State
The session object stores the information about a session (like session key). It may also store other information in the form of session variables. The collection of values stored in session object is called session state.

State Management
The management of session state is called state management. Different server technologies implement different mechanisms for the state management. ASP.net supports both, client side state management as well as server side state management.

At client side, following techniques are used for state management:
- Cookie
- Hidden Field
- View State
- Control State
- Query String

At server side, following are the techniques, used for state management:
- Application State
- Cache Object
- Session State
- Database

In ASP.net, there are three ways to manage session state:

- In-process session state
- Out-of-process session state
- database

These states are configured in web.config file's session state element.
<SessionState mode="Off | InProc | StateServer | SqlServer | Custome" />

InProc Session State
when session state is InProc, objects are stored as live reference in the HttpRuntime Internal Cache. The session state is held in memory.
- If worker process or application domain recycles, all session data is lost.

- If a web site is maintained on more than one machine, a user may be redirected to any other machine. when the user returns to the original machine, a fresh empty session is created. So InProc session state will not work here.

- If web gardening is used on a multi processor system, where each worker processor has an affinity for a particular CPU, don't use InProc session state.

Accessing Session Object:
the EnableSessionState of @Page directive controls the access to a session object for a page. The different values for EnableSessionState attribute are:
- (i) True: read/write access to session object. Acquires a write lock on the session object. No other page, requested from the same session, can access session object.
- (ii) False: no access to session object.
- (iii) ReadOnly: Only readonly access to session object. Acquires a reader lock on the session object.

Out-of-process Session State
when mode is set to state server in web.config, ASP.net maintains out-of-process session state. Out of process session is maintained by aspnet_state.exe file. It runs as a window service and listenes to TCP port 42424. The port can be changed using the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\Port.
The aspnet_state service is not started by default. It can be started using MMC service or by running following command:
net start aspnet_state.

To use out-of-process, mode is set to StateServer in config.sys file.
<Configurattion>
<System.Web>
  <SessionState mode="StateServer" StateConnectionString = "tcpip=127.0.0.1:42424" />
</System.Web>
</Configuration>

Since session state is managed on the local machine, so local host's IP is given. You may use a separate machine as state server. In that case, IP of state server should be given in the StateConnectionString. 42424 is the default port. Any port may be used after changing the registry but it should be open.

Out-of-process session state leaves the worker process (aspnet_wp.exe or w3wp.exe) and enters into the state process (aspnet_state.exe). Therefore out-of-process state can't be stored as reference. The objects are passed between processes in binary serialized form. So any object which is used in out of process session state must be instantiated from a serializable class.

A class can be made serializable in the following way:
VB.NET
<Serializable()> _
Public Class MyClass
...
End Class

C#


[Serializable]
public class MyClass{
...
}

SQL-Backed Session State
skipped for now.

Cookie-less session state
Include cookiless = "UseUri" in web.config file.
<SessionState Mode = "InProc" Cookieless = "UseUri" />

In Cookieless session state session-id is embedded into the URL. it seems to be a directory in the URL path.
- The session key consists of ASCII values and visible to everyone. They can be easily tempered.
- The session is lost, if a relative URL is invoked directly by typing its address. This is because, in this case session key will not be embedded in to the URL.
- To generate URL at server side, HttpResponse.ApplyAppPAthModifier method should be involved. For example
Response.Write(Response.ApplyAppPAthModifier("foo/bar.aspx")

View State
View State is a encrypted hidden field which contains the key-value pair of the values of controls at a page. ViewState can be enabled or disables using the enableViewState attribute of @Page directive. The web server controls also have this attribute.

Objects or variables can be added to view state manually as follows:
ViewState["MyKey"] = myKey

Any object, which is to be added to the view state must be derived from a serializable class.

Since view state is encrypted, a developer cannot look into it. Some tools are available to examine the view state. One such tool called View State Decoder is available at http://www.pluralsight.com. Some tips on using view state are also available at www.hanselman.com/blog/searchview.aspx/q=viewstate. A tool to generate machine key is also available at pluralstate.com/tools.aspx.

Securing View State
The <machinekey> element of web.config is used to assign validation key to view state. A algorithm is used to protect view state.
<machineKey  ValidationKey = "AutoGenerate, IsolateApps"
  decryptionKey = "AutoGenerate, IsolateApps"
  validation = "SHA1" />

ASP.net automatically generate a 128 bit key. IsolateApps tells ASP.net to generate a unique key for each application using application's id. The available validation methods are SHA1, MD5 and 3DES. SHA1 and MD5 are used for temper-proofing while 3DES is used for encryption.

At the page level, in the <pages> configuration, Auto or Always values can be specified to viewStateEncryptionMode attribute. Auto encrypts the view state only when a control requests encryption using Page.RegisterRequiresViewStateEncryption method. Always specifies that the view state should be encrypted always.

Series of Events during The Life of A HTTP Request:

Begin Request
Authenticate Request
determines who the user is
Authorize Request
determine rights of user
Resolve Request Cache
determine weather request can by-pass additional processing
Acquire Request State
session state associated with request is about to be acquired
PreRequest Handler execute
application code of page execute at this point. HTTP handler is called
Post Request Handler Execute
get fired just after HTTP handler is called
Release Request State
session state is stored based on web.config setting
Update Request Cache
resulting output is ready to be added to cache
End request

Popular posts from this blog

Redirecting to new window in c#

CBSE Class X Result 2010 – How to Calculate Percentage