Tutorial : Session State in Asp.Net

Leave a Comment

Session state is associated with a browser session. A session starts when the client at first opens an ASP.NET page on the server, and ends when the client does not access the server for 20 minutes.

You can define your own code that should run when a session starts or ends within the Global Application Class.

To create Global Application Class Right Click Website -> Add New Item -> Global Application Class. With a new Global Application Class, the file global.asax is created.

Session State in Asp.Net

Inside this file some event handler routines are defined:

global.asax

<%@ Application Language="C#" %>
<script runat="server">
    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
    }
   
    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)
    {
        // Code that runs when a new session is started
    }
    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends.
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer
        // or SQLServer, the event is not raised.
    }
</script>


Session state can be stored within an HttpSessionState object. The session state object that is associated with the current HTTP context can be accessed with the Session property of the Page class. In the Session_Start() event handler, session variables can be initialized; in the example, the session state with the name mydata is initialized to 0.

void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        Session["mydata"] = 0;
    }


Reading session state, again, can be done with the Session property using the session state name:
Default.aspc.cs

protected void Page_Load(object sender, EventArgs e)
    {
        int val = (int)Session["mydata"];
        Label1.Text = val.ToString();
        val += 4;
        Session["mydata"] = val;
    }


To associate the client with its session variables, by default ASP.NET uses a temporary cookie with a session identifier. ASP.NET also supports sessions without cookies where URL identifiers are used to map the HTTP requests to the same session.

0 comments:

Post a Comment