How to Set Session Timeout in ASP.NET

To set the session timeout in an ASP.NET application, you can modify the sessionState element in the web.config file or programmatically adjust the session timeout value in the code.

  1. Setting Session Timeout in web.config:
    Locate the web.config file in the root directory of your ASP.NET application and find the '<sessionState>' element. Add or modify the timeout attribute to specify the desired timeout duration in minutes. For example, to set the session timeout to 60 minutes:

    <configuration>
      <system.web>
        <sessionState timeout="60" />
       </system.web>
    </configuration>

  2. Setting Session Timeout Programmatically:
    If you need more flexibility and want to set the session timeout dynamically based on certain conditions, you can adjust it programmatically in your code.
    In your ASP.NET code-behind file or Global.asax file, you can access the session state object and set its timeout property. Here's an example of setting the session timeout to 60 minutes in C#:

    // Set session timeout programmatically
    protected void Session_Start(object sender, EventArgs e)
    {
        // Set the session timeout to 60 minutes
        Session.Timeout = 60;
    }

  3. You can place this code in the Global.asax file inside the Session_Start event handler, which is triggered when a new session is started.

Remember to choose the appropriate method based on your specific requirements. If you want a static session timeout that applies to the entire application, modifying the web.config is the way to go. On the other hand, if you need dynamic control over the session timeout, programmatically adjusting it can be more suitable.

<configuration>
  <system.web>
      <sessionState mode="InProc" cookieless="true" timeout="60"/>
   </system.web>
</configuration>

  • The <configuration> element is the root element of the web.config file.
  • The <system.web> element contains configuration settings related to ASP.NET web applications.
  • The <sessionState> element defines the configuration for session state management in the application.
  • The mode="InProc" attribute specifies that the session state should be stored in the memory of the web server (in-process mode) rather than using an external state store.
  • The cookieless="true" attribute indicates that cookies should not be used for session identification, and instead, session IDs will be embedded in the URLs. 
  • This allows users to maintain session state even if they have disabled cookies in their browsers.
  • The timeout="60" attribute sets the session timeout duration to 60 minutes. After 60 minutes of inactivity, the session state data will expire.
This configuration ensures that session state is managed within the web server's memory, uses URL-based session IDs, and has a timeout of 60 minutes.

Popular Posts