Session and Cookies Management in ASP.NET

Manage Session and cookies in ASP.net, Perform Login, and Logout in asp.net, Logout with Sessions in asp.net, Logout using Session in asp.net. In this aps.net tutorial, We will perform hands-on examples on all of these operations.

What is a Session?

The session is usually used to identify a user. For example– if one user is login into any dynamic website. Data will display based on the user’s profile and another user is also login into the same website then that user will get data according to his profile.

In the background, the process which runs to identify the users is called a session.

There are two main things, Browser, and Server. when a user login into any application then a new session is created. This is created into the pool. And a session-id will generate and save in the form of cookies into the browser.

Session values are more secured because they are saved in binary or encrypted form and can only be decoded by the server. When the user shuts down the machine the session value will delete automatically. We must save the values in the database for keeping them forever.

Session Example in ASP.net

Here we can create a web application in ASP.NET which uses the session to understand the session let’s see the below example,

Step1:

Open your Visual Studio > Click on New Project >Select Web > then Select ASP.NET Empty Web Application > Name the application > Click on OK.

Step2:

Click on Solution Explorer > Right click on the project name > Add > New Item > choose Web Form > click on  Add.

add one more web form just like above step the both forms default name will be WebForm1.aspx and WebForm2.aspx respectively.

Step3:

Now add the following code into the WebForm1.aspx between the <div> </div> tags.

<div>
User Name:-
<asp:TextBox ID="tbUserName" runat="server"></asp:TextBox>
<br />
<br />
Password:-
<asp:TextBox ID="tbpwd" runat="server" ></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
</div>

Now click on the WebForm1.aspx.cs tab and add the following code in the Button1_Click section.

protected void Button1_Click(object sender, EventArgs e)
        {
            Session["UserName"] = tbUserName.Text;
            Session["Pwd"] = tbpwd.Text;
            Response.Redirect("WebForm2.aspx");
        }

the design of the WebForm1 will look like this.

Step4:

Now add the following code on the WebForm2.aspx between the <div> </div> tags.

 <div>
User Name:-
<asp:TextBox ID ="tbUserName" runat="server" ></asp:TextBox>
<br />
<br />
Password:-
<asp:TextBox ID="tbpwd" runat="server" ></asp:TextBox>
<br />
</div>

then click on the WebForm2.aspx.cs and add the code in Page_Load section.

protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserName"] != null)
            {
                tbUserName.Text = Session["UserName"].ToString();
            }
            if (Session["Pwd"] != null)
            {
                tbpwd.Text = Session["Pwd"].ToString();
            }
        }

the design of WebForm2 will look like this.

Step5:

Now for setting the session we have to use config file. Go to the Solution Explorer window Double click on the Web.Config

Now add the following code just below the <system.web> tag and above the <compilation> tag.

 <system.web>
<sessionState mode ="SQLServer" sqlConnectionString ="Server=DIVS\SQLEXPRESS;Integrated Security=true">
</sessionState> 
<compilation debug="true" targetFramework="4.0" />
</system.web>

Step6:

Run the Web Application.

Output:

first the WebForm1.aspx will show and when we enter inputs in both textboxes and click on Submit button.

then the next page that is WebForm2.aspx will show which is using the session to identify the user who is requesting to the server for a webpage.

What is Cookies?

In the browser, a cookie is a small piece or chunk of the memory for a specific browser. That piece is a simple text (a unique key) that is used to exchange the information between browser and server. Cookies are generally used to personalize the web experience because they keep track of the performance of the user.

A cookie is a small text file that saves on the user’s computer. For a cookie the maximum file size is 4KB. It is also known as HTTP Cookie(Hyper Text Transfer Protocol Cookie), an internet cookie, or a web cookie. When a user visits any website, the site sends the data packets to the user’s computer in a form of a cookie.

Information that is stored in cookies is not safe because it is kept on the client-side in a text format that can be seen by anybody. We can only do is to activate or disable the cookies based on our needs.

Cookies Example in ASP.NET

Here we can create a web application in ASP.NET which uses the HTTP Cookie to understand the Cookies let’s see the below example,

Step1:

Open your Visual Studio > Click on New Project >Select Web > then Select ASP.NET Empty Web Application > Name the application > Click on OK.

Step2:

Click on Solution Explorer > Right click on the project name > Add > New Item > choose Web Form > click on  Add.

add one more web form just like above step the first form we have added leave it with the default name which is WebForm1.aspx and while adding the second form change its name to Default.aspx .

Step3:

Now add the following code into the WebForm1.aspx between the <div> </div> tags.

<div>
<asp:Label ID ="Label1" runat ="server" Text ="Label"></asp:Label>
</div>

Now click on the WebForm1.aspx.cs tab and add the following code in the Page_Load event.

 protected void Page_Load(object sender, EventArgs e)
        {
            HttpCookie cookie = new HttpCookie("student");
            cookie.Value = "Nida Khan";
            Response.Cookies.Add(cookie);
            var co_val = Response.Cookies["student"].Value;
            Label1.Text = co_val;
        }

the design of the WebForm1 will look like this.

Step4:

Now add the following code on the Default.aspx between the <body> </body> tags.

<head runat="server">
<title>"Home Page"</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Select Brand" ></asp:Label>
<br />
<br />
<asp:CheckBox ID="Apple" runat="server" Text="Apple" />
<br />
<asp:CheckBox ID="Redmi" runat="server" Text="Redmi" />
<br />
<asp:CheckBox ID="Samsung" runat="server" Text="Samsung" />
<br />
<asp:CheckBox ID="Oppo" runat="server" Text="Oppo" />
<br />
<asp:CheckBox ID="Vivo" runat="server" Text="Vivo" />
<br />
<br />
<asp:Button ID=Button1 runat="server" OnClick="Button1_Click" Text="Submit" />
<p>
<asp:Label ID="Label2" runat="server"></asp:Label>
</p>
</form>
</body>

then click on the Default.aspx.cs and add the code in Page_Load section.

 protected void Page_Load(object sender, EventArgs e)
{
Response.Cookies["Mobile"].Expires = DateTime.Now.AddDays(-1);
}

then click on the design section and by clicking on the button the Button1_Click section will show write the below code there.

 protected void Button1_Click(object sender, EventArgs e)
        {
            Label2.Text = "";
            if (Apple.Checked)
                Response.Cookies["Mobile"]
                    ["Apple"] = "Apple";
            if (Redmi.Checked)
                Response.Cookies["Mobile"]
                    ["Redmi"] = "Redmi";
            if (Samsung.Checked)
                Response.Cookies["Mobile"]
                    ["Samsung"] = "Samsung";
            if (Oppo.Checked)
                Response.Cookies["Mobile"]
                    ["Oppo"] = "Oppo";
            if (Vivo.Checked)
                Response.Cookies["Mobile"]
                    ["Vivo"] = "Vivo";
            if (Request.Cookies["Mobile"].Values.ToString() != null)
            {
                if (Request.Cookies["Mobile"]["Apple"] != null)
                    Label2.Text += Request.Cookies["Mobile"]["Apple"] + "";
                if (Request.Cookies["Mobile"]["Redmi"] != null)
                    Label2.Text += Request.Cookies["Mobile"]["Redmi"] + "";
                if (Request.Cookies["Mobile"]["Samsung"] != null)
                    Label2.Text += Request.Cookies["Mobile"]["Samsung"] + "";
                if (Request.Cookies["Mobile"]["Oppo"] != null)
                    Label2.Text += Request.Cookies["Mobile"]["Oppo"] + "";
                if (Request.Cookies["Mobile"]["Vivo"] != null)
                    Label2.Text += Request.Cookies["Mobile"]["Vivo"] + "";
            }
            else Label2.Text = "Please select your choice";
            Response.Cookies["Mobile"].Expires = DateTime.Now.AddDays(-1);

        }

the design of Default.aspx/Homepage will look like this.

Step5:

Run the Web Application.

Output:

In this web form select check boxes and then  click on Submit button.

after selection the checked check boxes values will display as it stores in the form of HTTP Cookies.

so these are the simple examples which uses the session and cookies in ASP.NET.