«

»

Oct 10

Session and Cookie in ASP.NET

Session and Cookie are two important concepts for state management in Web application.  Web server does not record each and every request in server memory, and it thinks each and every request is a new request.

we can use various techniques like hidden field storage, Session storage, Store in Cookie, Store in ViewState etc. we describing here two state maintain mechanisms called Session and Cookie 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 technique state management in Web Application. Session is user specific means for each and every thread Session variable get create. Actually session use key value pair to store data internally.

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”]);
}
}
}

Above example is showing session variable store and fetch using key.

Session using Index

Session using index to process data from 0th position in session variable. We are showing here some example of session variable storing using index.

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 in web application. But session store in server memory and cookies store in client’s machine.

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);
        }
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>