Understanding and Configuring Session in Asp.Net

 

Whenever user visits any web application means they started new session with the application and it generates the new session id. The session id is stored in user browser cookie, but server can change session id storage in URL instead of  cookie.

 

Asp.Net allows you to create your own session id with own value. Session is nothing but key value pair like dictionary element in Asp.Net. Create session variable in Asp.Net as shown below.

 

Session["Id"] = "This is session variable";

 

Here Id is the key and "This is session variable" is the value.

 

Configuring Sessions:

 

Asp.Net allocates unique random 120-bit Session Id which stores in Cookie or URL. For each request in particular session, this id will pass from browser to server and server to browser.

 

By default session stores in Cookie, if you don't want to store session in Cookie you can mention cookieless as true in web.config as shown below.

 

<?xmlversion="1.0"?>

<configuration>

  <system.web>

    <sessionStatecookieless="false"></sessionState>

  </system.web>  

</configuration>

 

Session expires in 20 minutes by default if the user is inactive. If you want you can change the expiration period in web.config as shown below.

 

<?xmlversion="1.0"?>

<configuration>

  <system.web>

    <sessionStatetimeout="10"></sessionState>

  </system.web>

</configuration>

 

Here we change the idle time to 10 minutes from 20 minutes. If you want you can turn off the session for entire application in web.config as show below.

 

<?xmlversion="1.0"?>

<configuration>

  <system.web>

    <sessionStatemode="Off"></sessionState>

  </system.web>

</configuration>

 

If you want to disable session for specific page disable the session in page directive as shown below.

 

<%@ Page Language="C#" EnableSessionState="False" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>