How to use session and cookie in c# .NET
Session and Cookie in ASP.NET
Session and Cookie are two important concepts in Web
application. As we know Web application is persistence in nature means Web
server does not record each and every request in server memory, and it thinks
each and every request is a new request.
Now, to preserve persistency between requests we can use
various techniques like hidden field storage, Session storage, Store in Cookie,
Store in ViewState etc. In this article we will see two popular state maintain mechanisms
called Session and Cookie. We will implement each concept with simple code
snippet. We will be using C# as backend language of Web application. But in any
server side language the basic concept is same only syntax is different.
Session using Key
Session is most popular state management technique in Web
Application. It is user specific means for each and every thread Session
variable get create. Actually session use key value pair to store data
internally. We can store and fetch data in session variable both by key and index.
At first we will see how to access session variable by Key.
Access session variable by Key
Here we are specifying name as a key of session variable and
using same key we are fetching data from session state.
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebTest
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Session["Name"] = "Sourav Kayal";
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Write(Session["Name"]);
}
}
}

Session using Index
In this example we will be using index to process data in
session variable. In 0th position we are setting some value and
using same index we are retrieving value from session state.
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Session[0] = "Session using Index";
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Write(Session[0]);
}
}

Cookie
Like session cookie also used to maintain state between requests.
But the key concept is that session store in server memory but cookies store in
client’s secondary storage device.
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebTest
{
public partial class WebForm1 : System.Web.UI.Page
{
HttpCookie Cook;
protected void Page_Load(object sender, EventArgs e)
{
Cook = new HttpCookie("MyCookie");
}
protected void Button1_Click(object sender, EventArgs e)
{
Cook.Value = "My Cookie";
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Write(Cook.Name);
}
}
}
