Asp.net Session expiring automatically after few seconds - asp.net

When user login i am storing user_id in Session variable and on second page i am checking on page load if user_id exists then fine, otherwise redirect to sign in page but when i login and and redirected to next page after few seconds when i refresh page my session is null there and i am redirected to sign in page its happening in whole application i have tried all solutions but all in vain
Another thing is that application working fine on development server and also on local IIS in LAN but on live server this issue is occurring.
Kindly suggest solution, i am also defining session time out in minutes and mode in Proc in web.config.
Thanks in advance

If you are using InProc session state mode and multiple worker processes in the application pool then Session might expire automatically after few seconds as data loss can occur if different requests for the same session are served by different worker processes.
In my case, I am using InProc session state mode with Maximum Worker Process set to 4 hence session was expiring.
Setting Maximum Worker Process = 1 solved it.

You can add <httpRuntime delayNotificationTimeout=""/> in your web.config. see more
OR
Try this
<authentication mode="Forms">
<forms loginUrl="/loginurl" timeout="2880" />
</authentication>

try this in web.config
<configuration>
<system.web>
<sessionState mode="InProc" timeout="90"></sessionState>
</system.web>
</configuration>

One session issue I just ran into, which may help here, is that users from certain companies would have their sessions end fairly quickly but other users had no problem. After doing a lot of testing, I found that users connecting to the website from their office were having problems but the same user connecting from home had no problem.
Their company is setup to use a single IP (or set of IPs) for all out bound web requests. Well, this company had multiple IPs for out-site access and that IP changed (or could change) with each request. This would reset the session on my website and log them out.
I am still in the process of implementing a fix or a check for this so I can't give you a fool proof fix, but it is something to look into. This would explain what is happening to you.

Any chance you're using a cluster of servers? Network load balancing might reroute the client to a different server every time. If so, either the NLB has to be reconfigured to keep a client on a single server or set up session sharing.
Also check that the application pool doesn't have some obscene rule to recycle itself too often.

Related

Troubleshoot Session Timeout Issues in ASP.NET

I'm having issues with session timeout issues with a public facing site that is utilized by several clients that may have various "secured" browser configurations. In general we have the session timeout set for 15 mins within the web.config. However, they are getting a timeout within a min or within 30 seconds or so for every page postback. Within our environment and with some other clients they have no issues and the timeout occurs as expected. We are unable to access their systems and know very little about their infrastructure. The only thing I'm thinking is they may have configuration to disallow cookies or delete/wipe them every few seconds etc. Not sure....
I'm at a loss on what to look at as within our web.config we set our sessionstate as follows.
<sessionState allowCustomSqlDatabase="true" cookieless="UseCookies" mode="InProc" sqlConnectionString="somestring Integrated Security=SSPI;pooling=true;encrypt=true;trustservercertificate=true" timeout="15">
If someone has ideas on where to look.

ASP.NET Session Timeout not effective unless cookieless=true

I am trying to make the session timeout in my application configurable.
When I put the following code in my web.config file it works fine:
<sessionState cookieless="true" timeout="1" />
That is, I can see my session times out after 1 minute. However, this code has the side effect of putting the session id in the url which is not desirable.
On the other hand, if I use the following code in my web.config, the session does not timeout for at least 1 hour or longer:
<sessionState cookieless="false" timeout="1" />
To determine that the session is in fact timing out, I am using the following code in my _Layout.cshtml:
#if (Session[MvcApplication._Ssn_UserName] == null)
{
Response.Redirect("~/Login/Index");
}
When the timeout is working, I see the user redirected to my Login page anytime they navigate to a different page or just hit the refresh button in the browser.
I see the same behavior when running from Visual Studio (IIS Express) or when running on IIS.
I've done a lot of searching online, and haven't discovered any correlation between the cookieless setting and the timeout behavior. Any ideas would be appreciated.
Try to use the iis session state setting as suggested below:
1)open iis and select your site.
2)select the session state feature
3)set the mode and cookie setting as per your choice:
session timeout value should not be set higher than 20 minutes (except in special cases) because every open session is holding onto memory. It should also not be set lower than 4 minutes because clients rarely respond within that time resulting in a loss of session state.so try to set like 5 minutes or more.
make sure there is no other session time out setting which conflicts with this setting like global.asax file setting or code-behind time out setting.
try to set the iis application pool ideal time out setting the same as session Tim out setting.
go to the Application Pool of the website --> go to advanced settings --> Process Model --> and change Idle Time-out

ASP.NET randomly losing session values

I've been searching for answers for quite some time on this as it continues to plague me. We store user login info and other data about the user's current activities in Session State (InProc). Every so often I get a Null Reference exception trying to use one of the session variables. It happens on random pages, with random Session variables. I have modified the web.config httpRuntime and compliation tags to prevent appPool restarts:
<httpRuntime requestValidationMode="2.0" waitChangeNotification="86400" maxWaitChangeNotification="86400" />
<compilation debug="False" strict="false" explicit="true" targetFramework="4.0" numRecompilesBeforeAppRestart="1000" />
I have set IIS to restart the app pool at 3am to make sure it doesnt restart when people are busy using the server. And I'm logging app pool restarts in the event log to make sure I know when its happening.
Dim runtime As HttpRuntime = GetType(System.Web.HttpRuntime).InvokeMember("_theRuntime", BindingFlags.NonPublic Or BindingFlags.Static Or BindingFlags.GetField, Nothing, Nothing, Nothing)
Dim shutDownMessage As String = runtime.GetType().InvokeMember("_shutDownMessage", BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.GetField, Nothing, runtime, Nothing)
Dim shutDownStack As String = runtime.GetType().InvokeMember("_shutDownStack", BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.GetField, Nothing, runtime, Nothing)
Dim evtSource As String = "ASP.NET"
Dim log As New EventLog
log.Source = evtSource
log.WriteEntry(String.Format("_shutDownMessage={0}{2}_shutDownStack={1}", shutDownMessage, shutDownStack, vbCrLf & vbCrLf), EventLogEntryType.Warning)
I get the event log entries when the app pool restarts.
The App Pool is NOT restarting when these errors happen.
When particular Session variables are lost, most of the other Session variables for the same user are still in place. Also, there are typically another 10-20 users logged into the site that are unaffected when it happens.
The user that gets the error will back up, go through the same pages again, and it will work fine.
I was having this problem on a Windows Server 2003 (32bit) running IIS6 with .NET 3.5 32bit and 4GB of memory.. As part of our server upgrades about a year ago we got a new webserver - Windows Server 2008 (64bit) running IIS 7 with 16GB memory. I upgraded the website to .NET 4.0 64bit. Still having the same problems on the new machine (usually 1-3 times per day - at random times through the day).
I cant make it happen in my debugging due to its random nature, but I do believe it happens randomly on our dev environment as well. The dev server has virtually the same specs as the production one.
Both environments are isolated and running as a single web server, not a part of a web farm.
I'm thinking that I may try to implement a State Server to get out of the InProc mode, but that's just another stab in the dark..
Other than trying the State Server, is there anything else I can do to identify when this happens or prevent it?
if your web app deployed on a server farm (more then one server web)
As you said you are using an InProc session and it may happen the user is redirect to a different server from the one where it is has been stored that session variable.
In this case you should go for an out of proc session as you have mentioned(Session State Server)
if you go for a State Server bear in mind the below just to prevent any other issue:
Since the Stateserver combines the ASP.NET Session ID with the IIS
application path to create a unique key, sessions issued for one of
the five new webs could not be found when accessed through one of the
other webs which is obviously extremely unfortunate in a weighted
round robin load balanced web farm
http://www-jo.se/f.pfleger/session-lost
have also a look at this logger to understand if the app recycle against your will:
http://weblogs.asp.net/scottgu/archive/2005/12/14/433194.aspx
http://blogs.msdn.com/b/tess/archive/2006/08/02/asp-net-case-study-lost-session-variables-and-appdomain-recycles.aspx
For anyone that is interested, or dealing with similar issues, I wanted to follow up with the cause of my problem here.
I implemented NCache out-of-process state server for Application Cache and Session State about 7 or 8 months ago. Unfortunately, moving the session out-of-process has not had any impact of my problem of losing random session variables during report selection on my site. And, as I had been unable to replicate this problem, I had not put more effort into trying to fix it until recently when another problem made the light go off in my head.
To get to the point - I was not overwriting the session variables somewhere that I didnt realize, but the problem was the user was opening up a second (or third) tab to compare report selection options side by side. We have several custom reports where the user can select multiple options to generate custom reports (think of it like a wizard control where there are several steps to create a custom report). If a user is on step 3 of 5, and then opens a new tab and starts going through the report selection process again, the new selections are overwriting the old selections b/c the 2 tabs shared the same session. I verified this was the case by opening multiple tabs and stepping through the selection process.
I am in the process of trying to distinguish between multiple report runs so that the selections for one report are stored using a unique session key from other report selections. That is proving difficult as well, but is not really related to the problem I thought I was having with missing session data.
If anyone finds this post and thinks they are losing session data randomly and cant replicate it, try debugging your site and opening multiple tabs. Stepping through both tabs at the same time illuminated the problem for me.
HTH
The session issues you are facing can happen because of multiple reasons
Session expiration : as you are using Inproc mode, sessions are
valid only for the sessiontimeout timeperiod. which is 20 mins by
default. try to use sessionstate tag in system.web section of your
web .config and set timeout value to a larger value.
Another Issue could be because of webfarms and web gardens. if
you have configured web farms and web garden for your web site.
Inproc session sharing can cause issues.
Process restarts: w3p process of your website is getting
restarted because of some issue in code. or memory leaks.
I ran into this problem because our server was setup to run https. The sessions would not be retained if I ran under simple http. However, the sessions were retained when running on https. So we setup a URL rewrite rule to always send the application to https if they came in via http.
In addition sessions will not work locally or on the server unless you are running https (note the S on the end of https), if you have the following in your web.config file:
<httpCookies httpOnlyCookies="true" requireSSL="true"/>
Since it took me a while to figure this one out, I thought I'd post this here in case it helps someone else too.
I ran into a situation where both IE and Chrome were randomly dropping session variables too. I searched and searched and everyone said the usual things...check domain name, check your IIS settings for cookies...etc.
My issue turned out to be a permissions thing.
In my web.config, I have a permission entry for a 'public' folder that can be accessed by the unauthenticated public.
<location path="public">
<system.web>
<authorization>
<allow users="*" />
<allow users="?" />
</authorization>
</system.web>
The problem was a public-side .js call to a HttpHandler that was NOT on the public side.
In an attempt to reuse code, I pointed both the secure and public side to code in the secure side. I guess as a side effect, it killed the session, without a very meaningful error message.
I may add another entry just for that handler, or I may make a public and a secure copy of that code (a less desired approach).
One more condition is there where sessions can loose its value.
You can use Fiddler tool to trace out this problem.
The most condition can be found when you some element like source not found in solution. At that moment server will try to reload that unfounded or lost object by restarting the project. Restarting the project will resulted into resetting all session objects.
Thanks.

Updating an existing asp.net website kicks off users

When I update an ASP.NET Website [note: it's not a Web Application] running on a customer server by overwriting it with the latest version it currently kicks all the users off.
I'd prefer to be able to deliver a new version of a site without kicking off users - is there a way to minimise the chance that users will get kicked off? [apart from the obvious one of waiting for a time of low-usage]
If I moved from InProc to Session State I guess this might do the trick - but is there any other method?
Chaning away from InProc Session State should help.
The problem now is that any time your app is reset in IIS (overwriting the web.config will cause a restart), the IIS Worker process restarts and clears your session info.
Check out this MSDN Page to read the limitations of In-Process Session State:
Session State - MSDN
I think additionally to what you are suggesting, it will be appropriate to display an "update in progress..." page instead of kicking off users. You can do that by changing your web.config file.
Session IDs are valid for the lifetime of the application pool, or until (I believe) 20 minutes following the last page request from the client in question. This is configurable in web.config:
<configuration>
<system.web>
<sessionState
cookieless="false"
timeout="20"
</sessionState>
</system.web>
</configuration>
If the application pool is recycled, files within the application are updated, etc, your session IDs will be invalidated. For this reason it is considered wise to deploy your site during off-peak hours.
Design your application to not rely on the existence of session state variables. Use cookies for authentication (or integrated auth) and check for session variables as you use them; reload them if they don't exist.

Asp.net forms authentication cookie not honoring timeout with IIS7

Authentication cookies seem to timeout after a short period of time (a day or so). I am using Forms Authentication and have the timeout="10080" with slidingExpiration="false" in the web.config. With that setting, the cookie should expire roughly 7 days after the user is successfully authenticated.
This worked as advertised with IIS6, but when I moved the site to IIS7, the cookie expires much quicker. I've confirmed this behavior on multiple machines with IE and Firefox, leading me to believe it's an IIS7 setting.
Is there a hidden setting that is IIS7 specific related to authentication? All other authentication types are disabled for the website, except for anonymous user tracking.
The authentication cookie is encrypted using the machineKey value from the local web.config or the global machine.config. If no such key is explicitly set, a key will be automatically generated, but it is not persisted to disk – hence, it will change whenever the application is restarted or "recycled" due to inactivity, and a new key will be created on the next hit.
Resolving the problem is as easy as adding a <machineKey> configuration section to web.config, or possibly (preferably?) to the machine.config on the server (untested):
<system.web>
...
<machineKey
validationKey="..."
decryptionKey="..."
validation="SHA1"
decryption="AES"/>
...
</system.web>
Google generate random machinekey for sites that can generate this section for you. If your application deals with confidential information, you might want to create the keys yourself, though.
My understanding is that cookies are expired by the consuming party - the browser, which means that IIS has no say in this
Set session state configured in IIS as
In Process
Use Cookies
Time out = your required time
Use hosting identity for impersonation
Also set EnableSessionState to true (which is default too)
And most importantly run the app pool in classic mode.
Hope your problem will solve.
First of all i must say that these "guidelines" are generic and not iis-7 exclusive.
In web.config under <system.web>
you either have <sessionState mode="StateServer" stateConnectionString="tcpip=localhost:42424" timeout="130" cookieless="false"/> (which requires the ASP.NET Session State Server service running on localhost)
or <sessionState mode="InProc" timeout="130" cookieless="false"/>.
The main difference is that in InProc that session state data are placed in the application process itself. In the other setting a different service is doing the storage, and you application just polls it to get the required data.
Having used both (as well as sql-server session state mode) the InProc is the least reliable but the fastest. The Sql-server is the most reliable and the slowest and the StateServer mode is somewhere in the middle being unreliable only in the case of a power/system failure. Having said that, i must say that for site with a low request count the performance penalty is negligible.
Now, my experience has shown that InProc is quite unpredictable on its stability; i used to have the same problem with you. I was able to extend the stability of the application by tweaking the settings of the application pool, i removed the problem altogether by switching to SessionState (which also allows to bring down the application and not lose session state data).
The reasons that you may suffer from application/session stability:
IIS and application pooling. Each virtul directory of a website is assigned to an application pool (by default to "DefaultAppPool") which has a series of settings amongst which you define the interval that the process is "recycled" - and as such preserve system resources. If you don't change the settings the application may trigger one of the criteria for the process recycler, which means that your application is busted
Antivirus.
In a ASP.NET application if the web.config (and any child .config files the application depends on) file is touched the application is restarted. Now there are cases where an antivirus program may touch the web.config file (say once a day?) and as such the application is restarted and session data is lost.
Bad configuration
Specifically for Forms Authentication the time-related settings and behavior always where dependent on the web-session with the auth-session being under the web-session.
What i don't know is if the Forms Authentication module depends only on Session domain or if it also places data in the application domain as well. If the second is the case then you may have to disable all recycling settings in the Application Pool as well as checking again configuration/antivirus and who stores the session data.
I recently had the same problem where my site was timing out every 20 minutes even though I set the session timeout to 2 hours. I found that it was because IIS worker process was timing out every 20 minutes: http://technet.microsoft.com/en-us/library/cc783089(WS.10).aspx

Resources