Session variable timeout in asp.net application

In my web application, I use some session variables that are set at login:

eg. Session("user_id") = reader("user_id")

I use this through my application.

When the session variable ends, it causes errors, mainly when connecting to the database, because some requests require session("user_id") .

How can I set session variables so that as soon as they are confined to the login page, or how can I increase the time available?

+7
source share
4 answers

I assume that you are using forms authentication. The trick here is to ensure that your forms authentication expires before the session.

I wrote about this in this answer here:

How to redirect to login page when session expired (ASP.NET 3.5 FormsAuthen)

For example:

Set up your forms authentication - this sets a timeout of 60 minutes:

 <authentication mode="Forms"> <forms defaultUrl="~/Default.aspx" loginUrl="~/Login.aspx" slidingExpiration="true" timeout="60" /> </authentication> 

Extend the session longer:

 <sessionState mode="InProc" cookieless="false" timeout="70"/> 

In your Login.aspx code behind you can also do Session.Clear(); to delete stale session data before assigning session values.

+11
source

In the past, I used a base page or a main page on each page (making an exception for the login page) that reads the session token to find out if the user is currently logged in.

If it ever reads zero, it saves the current URL and redirects the login page.

After logging in, it reads the saved URL and redirects the user back to the requested page.

Increasing a session timeout value is a setting in IIS.

+1
source

How can I set session variables so that as soon as they are confined to the login page

Check if they are equal = null to do Response.Redirect("Home.aspx");

or how can you increase how much time they are available?

Its in the web.config file in the sessionState element

+1
source

I think many people end their session calls to create a lazy loading template. Something like that:

 class SessionHelper { public static string GetUserId() { string userId = (string)System.Web.HttpContext.Current.Session["UserId"]; if( userId == null ) { userId = reader("UserId"); System.Web.HttpContext.Current.Session["UserId"] = userId; } return userId; } } 
0
source

All Articles