There are two important objects which work on server.
State management is the technique that is used to maintain user and page information over multiple requests while browsing the web.
HTTP is a stateless protocol. It does not store any information about user on web page. It is a general requirement that information should be maintained while navigating the website.
Session provides that facility to store information on server memory not browse. It stores the user’s specific information. It can store any type of object. For every user Session data store separately, means session is user specific.
Storing the data in Session object
Session ["UserName"] = txtName.Text;
Retreving the data from Session object
Label1.Text = Session ["UserName"].ToString();
When we store data to Session state, a session cookie named is ASP.NET_SessionId is created automatically. It contains a unique identifier that is used to track the user while moving from one page to another page.
Important properties of Session object
Session Properties | Description |
---|
CookieMode | It specifies whether cookieless sessions are enabled.
Possible values are AutoDetect, UseCookies, UseDeviceProfile, and UseUri. |
SessionID | It provides the unique session identifier. It is secure enough and can't be decoded or hampered. When client communicate with server, only session id is transmitted, between them. |
Count | It provides the number of items in Session state. |
IsCookieless | Provides the information whether sessions are cookieless or not. |
IsNewSession | It determines whether session is new or not. |
IsReadOnly | It determines whether the Session state is read-only. |
Keys | Provides the list of item names stored in Session state. |
Mode | It determines the current Session state store provider. Possible values are Custom, InProc, Off, SqlServer, and StateServer. |
Important methods of Session object
- Abandon: It is used to end a user session.
- Clear: It clears all items from Session state.
- Remove: This method is used to remove a particular item from Session state.
Example:
using System;
using System.Web;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string info;
info = "CookieMode =: "+Session.CookieMode.ToString() + "</br>"; ;
info += "Count =: "+ Session.Count.ToString() + "</br>"; ;
info += "IsCookieless =: " + Session.IsCookieless.ToString() + "</br>"; ;
info += "IsNewSession =: " + Session.IsNewSession.ToString() + "</br>"; ;
info += "IsReadOnly =: " + Session.IsReadOnly.ToString() + "</br>"; ;
info += "Keys =: "+Session.Keys.Count + "</br>"; ;
info += "Mode =: "+Session.Mode.ToString() + "</br>"; ;
info += "SessionID =: " + Session.SessionID.ToString() + "</br>"; ;
Label1.Text = info;
}
}
Session Events
There are two events that session object supports. These two events are handled in Global.aspx file.
Whenever a new user sessions starts, Session_Start events fires. The Session_End event is raised when a session ends.
Example: Global.asax file
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
Application["UserCount"] = 0;
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
Application.Lock();
int count = (int)Application["UserCount"];
Application["UserCount"] = count + 1;
Application.UnLock();
}
void Session_End(object sender, EventArgs e)
{
Application.Lock();
int count = (int)Application["UserCount"];
Application["UserCount"] = count - 1;
Application.UnLock();
}
</script>
In the above example, the variable UserCount is incremented by one, whenever a new session begins.
The Session_End event is raised, when a session ends and the UserCount variable is decremented by one.
We can display the result on web page as follows:
void Page_Load()
{
Label1.Text = Application["UserCount"];ToString();
}
Session Times Out property
By default, the ASP.NET Framework provides 20 minutes as session timeout. We can change this time according to application need.
Be aware that when you increase the value of session timeout property more memory is consumed by your application.
You can specify the Session timeout in the web configuration file or you can do it programmatically.
<configuration>
<system.web>
<sessionState timeout="60" />
</system.web>
</configuration>
Session Mode
In ASP.NET there are following session modes available,
- InProc
- StateServer
- SQLServer
- Custom
- Off
By default, the Session state mode is InProc means Session state is stored in memory in the same process as the ASP.NET process. So accessing data is very fast. Another advantage is that there are no requirements of serialization to store data in InProc Session Mode.
There are two main disadvantages to storing Session state in the ASP.NET process.
- We can’t use in-process Session state with a web farm.
- All Session state is lost, if application restarts.
You can store Session data out-of-process.
You can choose
StateServer option for storing session data. It stores Session state in a Windows NT process.
SqlServer mode stores Session state in a SQL Server database. It is the most reliable and secure session management and Session data do not affected if we restart the IIS.
Custom mode stores Session state in a custom location.
If we set Session
Mode="off" in web.config, Session will be disabled for the application. For this we need to configure web.config in following way.
<configuration>
<system.web>
<sessionState mode="Off"></sessionState>
</system.web>
</configuration>
Session State Mode | State Provider |
---|
InProc | In-Memory Object |
StateServer | Aspnet_state.exe |
SQLServer | DataBase |
Custom | CustomProvider |
Cookieless Session State
If a user disables cookies in the browser, then Session state doesn’t work because by default, Session state depends on cookies. The ASP.NET Framework uses the ASP.NET_SessionId cookie identifier to identity the user while browsing the web.
If you want that Session state should work even when cookies are disabled, then you can use cookieless sessions.
You can enable cookieless sessions by adjusting the sessionState element in the web configuration file as.
<configuration>
<system.web>
<sessionState cookieless="AutoDetect" regenerateExpiredSessionId="true" />
</system.web>
</configuration>
Advantages and disadvantages of Session
Following are the basic advantages and disadvantages of using session.
Advantages:
- It stores user states and data to all over the application.
- Easy mechanism to implement and we can store any kind of object.
- Stores every user data separately.
- Session is secure and transparent from user because session object is stored on the server.
Disadvantages:
- Performance overhead in case of big number of user, because of session data stored in server memory.
- Overhead involved in serializing and De-Serializing session Data. Because In case of StateServer and SQLServer session mode we need to serialize the object before store.
Application State
Application object is used to store information at application level rather than user level. All pages of your application can access the Application object. Application variables are stored on a web server.
If you are using Application object, then you may face concurrency problem. To avoid this problem we should use the lock and unlock methods. Therefore if multiple thread requests came for same data then only one thread can do the work.
Writing data to Application object
Application["Message"] = "Hello to all";
We can use Application object in a scenario where we want to count the number of visitors of web site.
Application State variables are empty, when the process hosting the application is restarted
Difference between session state and application state
Application | Session |
---|
It works at application level rather than user level. | Session object is user specific. |
Application state is stored only in the memory on the server. | Session state is stored in inProc and outProc |
Application state does not depends upon client's cookies | Session object depends upon cookie or can be cookieless. |
Application state does not depend upon the current browser. | Session state has scope to the current browser only. |