In this article we will learn to use Session even if the Cookie of the user’s browser is disabled
As we know HTTP is a stateless protocol and every request to a web page is treated as a new request. Session is a way of maintaining state of a page. A session stores user specific data that persist across multiple page requests. We can store any type of object in a session.
Session["Name"] = " txtName.Text;
Here, both statements can be used to store value of the “txtName” TextBox in Session.
Similarly, we can also add any other object in the session, like a DataSet.
SqlConnection con = new SqlConnection(ConString);
SqlCommand cmd = new SqlCommand("SELECT * FROM Employee", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
To retrieve the session value, we can use the following code:
if (Session["Name"] != null)
txtName.Text = Session["Name"].ToString();
First, we check if a session with name “Name” exists. Then we put the session vaule in the TextBox.
How to Cookie-less Session
By default a session use cookie in background. To enable cookie-less session, we need to change some configuration in the Web.Config file. Follow these steps :
- Open Web.Config file
- Add a <sessionState> tag under <system.web> tag
- Add an attribute “cookieless” in the <sessionState> tag and set its value to “AutoDetect” like below:
<sessionState cookieless=”AutoDetect” regenerateExpiredSessionId=”true”/>
Possible values for “cookieless” attribute are :
- AutoDetect : Session uses background cookie if cookies are enabled. If cookies are disabled, then the URL is used to store session information.
- UseCookeie: Session always use background cookie. This is default.
- UseDeviceProfile: Session uses background cookie if browser supports cookies else URL is used.
- UseUri: Session always use URL.
“regenerateExpiredSessionId” is used to ensure that if a cookieless url is expired a new new url is created with a new session. And if the same cookieless url is being used by multiple users an the same time, they all get a new regenerated session url.
We have configured our “Web.config” file to enable cookieless session. Now, its time to test it.
Open Mozilla Firefox and Click on (Tools -> Options -> Pricacy)
Now on History group box select (Firefox will : Use custom settings for history)
Now uncheck (Accept cookeies from sites)
You will get an URL something like this :