Session State
Session State enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. It is one of the important state management variable in Asp.Net. It’s working on server side.Session provides a facility to store information on server memory. It can support any type of object to store along with our own custom objects. For every client, session data is stored separately, which means session data is stored on a per client basis.
Advantage of session state is that once you store your data in session and access that data from anywhere in the application across multiple pages. Advantage of session state over cookies is that session can store any type of data as well as complete dataset whereas cookies can store only small amount of data. Along with these advantages, some times session can cause performance issues in high traffic sites because it is stored in server memory and clients read data from the server.
Write Session
:
Session["UserName"] = "Asphelps"; |
Read Session:
if (Session["UserName"] != null) { string userName = Session["UserName"].ToString(); } |
Session Events
Session_StartSession_End
You can handle both these events in the global.asax file of your web application. When a new session initiates, the
session_start
event is raised,
and the Session_End
event raised when a session is abandoned or expires.
void Session_Start(object sender, EventArgs e)
{
// When a new session starts. Session variables can be initialised here
}
void Session_End(object sender, EventArgs e)
{
//When a session ends or time out. Used to free up per-user resources or log
information
}
|
Clear Session Values
We can clear the session stored value by following three ways
1. Abandon - End user session in the application.
2. Remove - Remove a particular session in the application.
3. Clear - Clear all session object.
Session.Remove("UserName"); // Remove UserName session Session.Abandon(); // End a user session Session.Clear(); // Clear all session items |
Key Points
When you are using session then session will expire after specific time. This time is known as session timeout. Default session timeout value is 20 minutes.
But you can increase session timeout using session's TimeOut propery by declaring on page or in Web.Config.
<system.web> <sessionState timeout="60" /> </system.web> |
0 comments:
Post a Comment