Does Session use cookies in Asp.Net?

It’s very confusing for many developers that session use cookies or not, and also a interesting interview question for .net developer 🙂 Let’s understand the relation between session and cookies-

Does session use cookies? Answer is- YES and NO.

One more confusion?

While using session in the application we have two things which are SessionID which is used to uniquely identify the session variables and Session Value which is the actual data stored in the session variables.

As session is a server side and cookies are client side state management techniques, so session actual data always stored on the server memory by default. The following list describes the available session storage modes-

  • InProc mode, which stores session state in memory on the Web server. This is the default.
  • StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  • SQLServer mode stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  • Custom mode, which enables you to specify a custom storage provider.
  • Off mode, which disables session state.

I hope it’s clear that session data is stored on the server and has no relationship with the cookies.

Now let’s understand the session keys storage types-

 

 

 

 

Session and cookies relationship are limited to only session keys not session value.

 

Session use cookies – Yes :  By default Session key is stored in an HTTP  non-persistent cookie that the client sends to the server (and server to client) on each request/responses. The server can then read the key from the cookie and re-inflate the server session state.

If we will try to run below code after disabled the cookies then it will not work that proves that session use the cookies.

Session use cookies – No : There is the possibility that browser does not support cookie or disabled, then asp.net can not create a cookie to store session keys. ASP.NET offers an alternative in the form of cookieless sessions. You can configure your application to store session keys not in a cookie, but in the URLs. This can be done by setting cookieless=”true” in the web.config file  as-

<configuration>
<sessionstate cookieless=”true” />
</configuration>

http://localhost/(lit3py55t21z5v55vlm25s55)/Application/SessionState.aspx

 

Programming is Easy…

Advertisements