Session State in ASP.NET

ASP.net allows us to save values using session state. We can use session state to store user specific information that is maintained between server round trips and between request for pages.Session state is similar to the application state. If different users are using our application, every user has its own session state and if a user leaves our application and then returns later after the session timeout period, session state information is lost and then the new session is created for the user. Once we add an application specific information to session state, the server manages the object. The following example shows that how to store the time the user last loaded a page in a session variable and then later retrieve the value by casting it to the appopriate type.

protected void Page_Load(object sender, EventArgs e)
    {
        Session["lv"] = DateTime.Now;
        if (Session["lv"] != null)
        {
            Label1.Text = Session["lv"].ToString();
        }
        else
        {
            Label1.Text = "No information about the last visit of the user";

        }

    }

If we don't want to use the Session state, we can improve performance by disabling the session state for the entire application by setting the SessionState property to Off in the Web.config file:

<configuration>
<
system.web>
<
sessionState mode="Off" />
</system.web>
</
configuration>

If we want to disable session for the particular page of an application setEnableSessionState="False". We can also set EnableSessionState page directive to ReadOnly to provide readonly access to the session variable.

By default, Session state uses cookies to track user sessions. The following example shows that how we use the cookieless session identifiers:

 <configuration>
<
system.web>
<
sessionState cookieless="true" regenerateExpiredSessionId="true" />
</system.web>
</
configuration>