Register Login

Session State in ASP.Net with Example

Updated Jun 09, 2019

Sessions are used in ASP to handle the user interactions with the web page or the web application. In ASP.NET session objects are an important component of any application or a modern website. Basic information like username, password, shopping cart information, and the location can be stored in these sessions. As the HTTP protocol is stateless, there may be a problem when information has to be sent to another web form. This is where the session come in handy. The following article will discuss the types of sessions, their usage, how to end a session, session objects, and the session modes.   

Introduction to Session in Asp.net

In ASP.NET a session is a technique used for state management and is used for storing the value of the server. Along with the user-defined objects, it can store other type of objects also. The server data is stored as client data and is securely kept. This data is separately stored for every user on the server.

Types of the session in asp.net

The different types of sessions in ASP.NET are as follows:

  • Inprocess – It is stored in the web.config file by the default.
  • SQL server session – It is stored in the database.
  • Outprocess – It is stored on the server side.

How to use sessions in ASP.NET?

Sessions in ASP.NET are used for identifying the requests received from a particular browser during a specific time period. For example, a web page wants the user to enter a name and a password that has to be sent to another web page. Session objects can be used here to send the contents of the web page. Multiple key-value pairs can be stored in these sessions. The sessions will store the data as cookies. This form of session management ensures that the data is sent properly from one web page to another.

For all applications the ASP.NET, the sessions are enabled. As ASP creates unique cookies for every user, the information is stored in the sessions.

How to create a session in asp.net?

A new session object is created for every user when the session starts and it is ended when the session expires. When a new user requests for an ASP file, a session OnStart procedure is included in the Global.asa file. The session gets started here. Just like a cookie, a value is stored in the session variable. The sessions that are created are stored in the SessionStateItemCollection object. The value of the current session can e obtained from the Session property of the Page object.

When a user raises a request for an ASP file the Global.asa file initializes the session scope using the <object> tag.

Example to Create a Session in Asp.net

using System;
using System.collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


public partial class _Default : System.Web.UI.Page{
    
    protected void Page_Load(object sender, EventArgs e)
    {

        if(Session["user"] != null){
            Response.Redirect("~/Welcome.aspx");
        }

    }

    protected void btnLogin_Click(object sender, EventArgs e)

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionString["connect"].ToString());

        con.Open();

        string query = "select count(*) from tblUsers where user_name = '"+txtUser.Text+"' and user_pass = '"+txtPass.Text+"'";

        SqlCommand cmd = new SqlCommand(query,con);

        string output = cmd.ExecuteScalar().ToString();

        if(output == "1")
            {
                Session["user"] = txtUser.Text;  // Creating a Session | Naming a session | Adding Value in session variable 
                                                    
                Response.Redirect("~/Welcome.aspx");
            }
        else
            {
                Response.Write("Login Failed");
            }    
    }
}

 How to store value in session in Asp.net?

Values can be stored inside a session object in ASP.NET. The following code can be used for storing values in any session:

<%
   Session(“age”)= 24
%>

If a value is stored inside a session variable it can be obtained from any page within the ASP application. User preferences can also be stored in the session objects. This information can be used to determine which page to display or return to the user.

Additionally, the In-Proc mode is the default mechanism for storing session data in the server’s memory. However, this mode should only be used when the data to be stored is not very important and which cause no problems if lost. This is because, in this mode, the data is not persisted and is available as long as the session is active.

How to kill session in Asp.net?

The sessions in ASP can be removed through the following methods:

  • The Session.Abandon() method can be used to kill the current session.
  • For removing or clearing value, the Session[“Item”]=null; has to be used.
  • The Session.Clear() method is used for removing all the keys from the session.

The contents collection has the contents of the session variables. The Remove method can be used to remove a session variable from the collection. For example, the remove all the variables in a session the following code can be used:

<%
   Session.Contents.RemoveAll()
%>

Example of How to Kill a Session in Asp.net

ASP.NET Session Events

An event is any occurrence mouse click, a key press, a mouse movement or a notification generated by the system itself. Any of such events that occur during a session are called session events. In ASP there are two types of events in sessions:

  • Session_Start – This event is raised when the session starts and the user makes a request for a web page from an ASP application. The required resources are initialized during this event like establishing a connection with a database.
  • Session_End – This event is raised when the session gets over.

Both of the events can be handled within the global.asax file of the application.

ASP.NET Session Modes

The different session modes are as follows:

  • InProc mode – This is the default session mode defining its state. It stores the state of the session within the memory object of the application. As this data resides within the same application domain where the application exists, the data retrieval process is easier.
  • StateServer mode – This mode is used to store data in a separate stand-alone server as a Window Service. So to retrieve the session data the user has to use another process. The Web.config file has to be configured to make this mode work.
  • SQL Server mode – The data in this mode is stored in the SQL database.
  • Custom mode – The custom storage option can be defined here.
  • Off mode – The mode is used to disable the session state.

Conclusion

Session states are easier to implement than the View states. The sessions help the user to access the required session data faster than other methods. This way the users are able to work in environments where multiple configurations are required. However, it is not advisable to use the session when working with a large dataset or a huge quantity of data, as the data is stored in the server.    

Complete Code

Default.apsx 

using System;
using System.collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page{
    
    protected void Page_Load(object sender, EventArgs e)
    {

        if(Session["user"] != null){
            Response.Redirect("~/Welcome.aspx");
        }

    }

    protected void btnLogin_Click(object sender, EventArgs e)

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionString["connect"].ToString());

        con.Open();

        string query = "select count(*) from tblUsers where user_name = '"+txtUser.Text+"' and user_pass = '"+txtPass.Text+"'";

        SqlCommand cmd = new SqlCommand(query,con);

        string output = cmd.ExecuteScalar().ToString();

        if(output == "1")
            {
                Session["user"] = txtUser.Text;  // Creating a Session | Naming a session | Adding Value in session variable 
                                                    
                Response.Redirect("~/Welcome.aspx");
            }
        else
            {
                Response.Write("Login Failed");
            }    
    }
}

web.config

<?xml version = "1.0"?>
<!-- For more information on how to configure your ASP.NET application, Please visit
http://go.microsoft.com/fwlink/?LinkId=169433 -->
<configuration>
    <system.web>
        <compilation debug="false" targetFramwork="4.0" />
    </system.web>

    <connectionString>
        <add name="connect" connectionString="Data Source=AMIT-PCSQLEXPRESS;Initial catalog=login_page;Integrated Security=True" providerName="System.Data.sqlClient" />
    </connectionString>
</configuration>

welcome.aspx

using System;
using System.collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(Session["user"] != null){
            txtuser.Text = "Welcome " + Session["user"].ToString();
        }

    }
    protected void btnLogout_Click(object sender, EventArgs e)
    {
        Session.Remove("user");    // Destroy a session or kill a session
        Response.Redirect("~/Default.aspx");
    }
}

 


×