How to maintain session in asp.net, HTTP is a stateless protocol. Actually statelessness is one of the many advantages of the World Wide Web. In a statelessness condition all information associated with the page and the controls on the page would be lost with each round trip. Round trip means a request from a user to Web Server and response from Web server to user. There is no standard way in which the server can determine whether a subsequent HTTP request is from the same user. To overcome this limitation of traditional Web programming, ASP.NET includes several features that help you preserve data on both a per-page basis and an application-wide basis by its State Management Capabilities. ASP.NET provides various options for state management such as Client-Based State Management Options and Server-Based State Management Options.
Here I explained about session management, session is one of the server side state management techniques.
Session is one of the most common ways which is being used by developers to maintain the state of the application. The Session basically stores the values as a dictionary collection in key/value pairs. It completely utilizes server resources to store the data. It is a secure way of storing data, since the data will never be passed to the client. For each and every user, a separate Session is created, and each and every Session has its Unique ID. This ID is being stored in the client’s machine using cookies. If there are multiple users who are accessing a web application, then for each user a separate Session is created. If a single user logs in and logs out the Session is killed, then if the same user again logs into the application, then a new Session ID is being created for the same user. The Session has a default timeout value (20 minutes). We can also set the timeout value for a session in the web.config file.
Session variables are stored in a SessionStateItemCollection object that is exposed through the HttpContext.Session property. In an ASP.NET page, the current session variables are exposed through the Session property of the Page object. The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are created by referring to the session variable by name. You do not have to declare a session variable or explicitly add it to the collection. The following example shows how to create session variables in an ASP.NET page for the first and last name of a user, and set them to values retrieved from TextBox controls. Session [“FirstName”] = txtFirstName.Text; Session[“LastName”] = txtLastName.Text; Note: When you use a session-state mode other than InProc, the session-variable type must be either a primitive .NET type or serializable. This is because the session-variable value is stored in an external data store.
Sessions are identified by a unique identifier that can be read by using the SessionID property. When session state is enabled for an ASP.NET application, each request for a page in the application is examined for a SessionID value sent from the browser. If no SessionID value is supplied, ASP.NET starts a new session and the SessionID value for that session is sent to the browser with the response. By default, SessionID values are stored in a cookie. However, you can also configure the application to store SessionID values in the URL for a “cookieless” session. A session is considered active as long as requests continue to be made with the same SessionID value. If the time between requests for a particular session exceeds the specified time-out value in minutes, the session is considered expired. Requests made with an expired SessionID value result in a new session.
SessionID values are sent in clear text, whether as a cookie or as part of the URL. A malicious user could get access to the session of another user by obtaining the SessionID value and including it in requests to the server. If you are storing sensitive information in session state, it is recommended that you use SSL to encrypt any communication between the browser and server that includes the SessionID value.
Cookie less SessionIDs:
By default, the SessionID value is stored in a non-expiring session cookie in the browser. However, you can specify that session identifiers should not be stored in a cookie by setting the cookieless attribute to true in the <SessionState> section of the Web.config file.
The following example shows a Web.config file that configures an ASP.NET application to use cookieless session identifiers.
<sessionState mode="InProc" cookieless="true" regenerateExpiredSessionId="true" />
ASP.NET maintains cookieless session state by automatically inserting a unique session ID into the page’s URL.
For example, the following URL has been modified by ASP.NET to include the unique session ID u1daopo5vmuwl55yenibg1zl: http://localhost/WebSiteHttp1/(S(u1daopo5vmuwl55yenibg1zl))/ViewEmp.aspx
When ASP.NET sends a page to the browser. It modifies any links in the page that use an application-relative path by embedding a session ID value in the links. (Links with absolute paths are not modified.) Session state is maintained as long as the user clicks links that have been modified in this manner. However, if the client rewrites a URL that is supplied by the application, ASP.NET may not be able to resolve the session ID and associate the request with an existing session. In that case, a new session is started for the request.
The session ID is embedded in the URL after the slash that follows the application name and before any remaining file or virtual directory identifier. This enables ASP.NET to resolve the application name before involving the SessionStateModule in the request.
Note: To improve the security of your application, you should allow users to log out of your application, at which point the application should call the Abandon () method. This reduces the potential for a malicious user to get the unique identifier in the URL and use it to retrieve private user data stored in the session.
Regenerating Expired Session Identifiers:
By default, the session ID values that are used in cookieless sessions are recycled. That is, if a request is made with a session ID that has expired, a new session is started by using the SessionID value that is supplied with the request. This can result in a session unintentionally being shared when a link that contains a cookieless SessionID value is used by multiple browsers. (This can occur if the link is passed through a search engine, through an e-mail message, or through another program.) You can reduce the chance of session data being shared by configuring the application not to recycle session identifiers. To do this, set the regenerateExpiredSessionId attribute of the configuration element to true. This generates a new session ID when a cookieless session request is made with an expired session ID.
Note: If the request that is made with the expired session ID is made by using the HTTP POST method, any posted data will be lost when regenerateExpiredSessionId is true. This is because ASP.NET performs a redirect to make sure that the browser has the new session identifier in the URL.
ASP.NET session state supports several storage options for session variables. Each option is identified by a value in the SessionStateMode enumeration. The default behaviour is to store session variables in the memory space of the ASP.NET worker process. However, you can also specify that session state should be stored in a separate process, in a SQL Server database, or in a custom data source. If you do not want session state enabled for your application, you can set the session mode to off.
There are four session storage mechanisms provided by ASP.NET:
InProc mode, which stores session state in memory on the Web server. This is the default. It offers much better performance than using the ASP.NET state service or storing state information in a database server. InProc is fine for simple applications, but robust applications that use multiple Web servers or must persist session data between application restarts should use StateServer or SQLServer.
StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. ASP.NET State Service is included with any computer set up to run ASP.NET Web applications. However, the service is set up to start manually by default. Therefore, when configuring the ASP.NET State Service, you must set the start-up type to Automatic.
SQLServer mode, stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web form.
Custom mode, which enables you to specify a custom storage provider. You also need to implement the custom storage provider.
Off mode, this disables session state. You should disable session state if you are not using it to improve performance.
Configuring Session State:
Session state is configured by using the <sessionState> element of the<System.Web> configuration section. You can also configure session state by using the EnableSessionState value in the @ Page directive. The <sessionState> element enables you to specify the following options:
- The mode in which the session will store data.
- The way in which session identifier values are sent between the client and the server.
- The session Timeout value.
- Supporting values that are based on the session Mode setting.
The following example shows a sessionState element that configures an application for any of the session mode.
<span style="color: #ff0000;"><Configuration>
<SessionState mode<span style="color: #0000ff;">=”InProc”|”SqlSever”|”StateServer”|”Custom”|”Off” <span style="color: #ff0000;">CookieLess</span>=”true”|”false”</span> timeout<span style="color: #0000ff;">=”Positive number Indicating the session timeout in minutes”</span>>
The settings above are used to configure ASP.NET session state. Let’s look at each in more detail and cover the various uses afterward.
- Mode. The mode setting supports three options: inproc, sqlserver, and stateserver. As stated earlier, ASP.NET supports two modes: in process and out of process. There are also two options for out-of-process state management: memory based (stateserver), and SQL Server based (sqlserver). We’ll discuss implementing these options shortly.
- Cookieless. The cookieless option for ASP.NET is configured with this simple Boolean setting.
- Timeout. This option controls the length of time a session is considered valid. The session timeout is a sliding value; on each request the timeout period is set to the current time plus the timeout value.
- Sqlconnectionstring. The sqlconnectionstring identifies the database connection string that names the database used for mode sqlserver.
- Server. In the out-of-process mode stateserver, it names the server that is running the required Windows NT service: ASPState.
- Port. The port setting, which accompanies the server setting, identifies the port number that corresponds to the server setting for mode stateserver.
You can disable session state for an application by setting the session-state mode to Off. If you want to disable session state for only a particular page of an application, you can set the EnableSessionState value in the @ Page directive to false. The EnableSessionState value can also be set to ReadOnly to provide read-only access to session variables. Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability
- In process mode (in-memory)- State information is stored in memory of web server
- Out-of-process mode- session state is held in a process called aspnet_state.exe that runs as a windows service.
- Database mode as session state is maintained on a SQL Server database.
InProc session state mode:
InProc mode is the default mode provided by ASP.NET. In this mode, session values are stored in the web server’s memory inside the asp.net worker process. If there are more than one IIS servers then session values are stored in each server separately on which request has been made. Since the session values are stored in server, whenever server (asp.net worker process) is restarted the session values will be lost. It is the only mode that supports the Session_End event.
<span style="color: #ff0000;"><configuration>
<sessionstate mode<span style="color: #0000ff;">="InProc”</span> cookieless<span style="color: #0000ff;">="false”</span> timeout<span style="color: #0000ff;">="20"</span> />
Advantages of InProc session state mode:
- Very easy to implement. All that is required is, to set, the session state mode=”InProc” in config file.
- Will perform best because the session state memory is kept on the webserver, within the ASP.NET worker process (aspnet_wp.exe).
- Suitable for web applications hosted on a single server.
- Objects can be added without serialization.
Dis-advantages of InProc session state mode:
- Session state data is lost, when the worker process or application pool is recycled.
- Not suitable for web farms and web gardens.
- Scalability could be an issue.
Sample session state application
before we use session state, we need an application to test it with. Below is the code for a simple C# application that writes to and reads from session state,
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,400italic,300italic,600,600italic,700,700italic,800,800italic' rel='stylesheet' type='text/css' />
font-family: 'Open Sans', sans-serif;
margin: 0 auto;
<form id="form1" runat="server">
<span>Enter name:</span><asp:TextBox ID="txtvalue" type="text" runat="server" name="text1"> </asp:TextBox><br /><br />
<asp:Button runat="server" Text="Add to Session State" ID="btnsubmit" OnClick="btnsubmit_Click" />
<asp:Button runat="server" Text="View Session State" ID="btnsubmitview" OnClick="btnsubmitview_Click" />
<asp:Button runat="server" Text="Remove Session State" ID="btnclear" OnClick="btnclear_Click"/>
<asp:Label ID="lblsession" runat="server"></asp:Label>
public partial class session : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
protected void btnsubmit_Click(object sender, EventArgs e)
Session["MySession"] = txtvalue.Text.Trim();
lblsession.Text = "Session data updated! <P>Your session contains: <font color=red>" + Session["MySession"].ToString() + "</font>";
protected void btnsubmitview_Click(object sender, EventArgs e)
if (Session["MySession"] ==null)
lblsession.Text = "NOTHING, SESSION DATA LOST!";
lblsession.Text= "Your session contains:<font color=red>" + Session["MySession"].ToString() + "</font>";
protected void btnclear_Click(object sender, EventArgs e)
Step1:Press ctrl+F5 or f5 ,To run the page on server
Step2: Enter the text in name filed.
Step3: Now, click on add to session state button it will maintain a session for name filed.
Step4: To see the session click on view sessionsate button ,it will returns your value until session default timeout end .
Step5:Now, click on remove session state button it will call the Abandon() Method of Session and clears the session .To check, click on view session state button it will show the below message
…follow the below link to get more interview questions in asp.net http://www.gofaqs.com/interview-questions/programming/asp-net and for previous tutorials http://gofaqs.com/training