Session variable loses value in asp.net application - asp.net

In my asp.net application I have a few session variables. Seems like only a few minutes on the localhost and also web host, they lose value. This happens periodically not all of the time. I do have cheap go daddy, web hosting, and that could be the problem on the web server. Thank you for any help, this is a big problem.
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="3600" defaultUrl="~/" name="" />
</authentication>
<sessionState mode="InProc" cookieless="false" timeout="80" />
public static User User
{
get
{
User userLogin = null;
object sessionVar = Session[USERLOGIN];
if (sessionVar != null)
{
userLogin = (User) sessionVar;
}
return userLogin;
}
set { Session[USERLOGIN] = value; }
}

There's a strong chance that your session is being wiped out on the server from the application pool being stopped and started, timeouts, or a host of other things. The main point is that session variables solely by themselves are unreliable persistent mechanisms.
If you need information to persist for a logged in user, try storing a cookie on the user's machine and if the session is null, repopulate it from identifying data in the cookie.

If I could comment I would, apparently I am not special enough ;P lol. I have to agree with KodeKreachor and Aristos on both points. I am not sure why there is a business/reasonable need to have the session state kept in memory.
To add to the points, mostly because I hate cookies, you could roll a solution to keep session states logged in a light weight database. I mean it really is all a cookie is for, flat file database record of information. SQLite might be a good solution, though unless I can find otherwise, you are rolling your own solution on that. Yes, as a loving Godaddy supporter, their cheaper services have a LOT to be desired. There is little to no control over what the system is doing with their shared hosting. My experience of hours talking to their tech department about what is and is not allowed can tell you that.
I would also mention that you might want to add some very verbose logging into the system using a solution such as Log4Net and then parse the logs for information on what is actually happening when the session state is being wiped. Then armed with that information move forward to find a much more clear solution.
Or just go easy on yourself and use cookies ;)
Just modify this for SQLite =D
HOW TO: Configure SQL Server to Store ASP.NET Session State
Of course here is a SQLite Session State Provider
SQLiteSessionStateStore
Apache Log4Net
Great Tutorial Series on using Log4Net by BeefyCode

Related

Asp.net Session expiring automatically after few seconds

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.

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.

Retrieve SSL session id in asp.net

Is there any way to retrieve the SSL session Id serverside in asp.net?
the short answer is no. This is an intentional limitation of IIS, so as to prevent people from taking a dependency on something that isn't dependable.
Out on the market, you will find various hardware load-balancers that will offer features like server persistence based on SSL Session ID, but they don't work very well because SSL renegotiation can happen at any time. In Internet Explorer 8, for example, a new SSL session is negotiated for every tab that is opened to a web site. You can expect similar behaviour from other multi-process browsers. So, I must stress that you should not use SSL Session ID for any kind of user identification purposes.
That said -- If you really need the SSL Session ID information for some specialized task, I recommend using Apache, mod_ssl and mod_proxy as a front-end to your IIS system. With a bit of fiddling, you could coerce mod_ssl into giving you the session ID, which you could then add to a proxied request to your IIS server as a query string parameter.... or you could store it in a database.
Tim,
Are you really "just" trying to retrieve the Session ID string or do you maybe lose all session information when switching to SSL? this would be a quite common problem, because the session on serverside is lost when using "InProc" session storage, and the session cookie on the client might be lost when not stored in a common domain.
Therefore, you should switch to state server or sql server session management in Web.config file, for example:
<sessionState mode="SQLServer"
cookieless="true"
regenerateExpiredSessionId="true"
timeout="30"
sqlConnectionString="Data Source=MySqlServer;Integrated Security=SSPI;"
stateNetworkTimeout="30" />
Beside that, I don't really know why you shouldn't be able to retrieve HttpContext.Current.Session.SessionID also in SSL mode as well.
Some MSDN Links:
MSDN: HttpSessionState.SessionID Property
MSDN: ASP.NET Session State Overview
Maybe this helps somehow.
Best regards

Session state. How to manage session with custom mode?

I am working on a website and this is my first web project.
Scenario for Session
I have created a database for my project with security level little bit high. I want to manage session for each and every user who is logging in to my website. Session state can be used using Cookie as well as URL, only one at a time.
Now I went over with all four session state modes.
i.e
1. InProc 2. State Server 3. Sql Server 4. Custom
Now after reviewing from all these modes I am in confusion which one should I use Sql Server or Custom.
Basically i want to store session related information in my own database instead of Aspnet_db which is a default database provided by microsoft. I have created all tables related to login and registration. But I dont know how to store session into my database.
What tables do I need to create so as to maintain into database.
I want to create a complete log of session and login related information into my database(Persistant atleast for 1 year).
I want to use machinekey as AES and SHA1.
<sessionState mode="Custom" cookieless="AutoDetect" timeout="15" regenerateExpiredSessionId="true" stateNetworkTimeout="10" >
</sessionState>
<machineKey decryption="AES"
validation="SHA1"
decryptionKey="7E047D50A7E430181CCAF7E0D1771330D15D8A58AEDB8A1158F97EEF59BEB45D"
validationKey="68B439A210151231F3DBB3F3985E220CFEFC0662196B301B84105807E3AD27B6475DFC8BB546EC69421F38C1204ACFF7914188B5003C1DCF3E903E01A03C8578"/>
<add name="conString" connectionString="Data Source=192.168.1.5; Initial Catalog=dbName; Integrated Security=True;" providerName="System.Data.SqlClient" />
What all things do i need to specify in webconfig ?
My Data Source= 192.168.1.5
Database name= db.mdf
What I need to know about
What tables do i need to add to my
database to store session related
information. eg. Session id (Any
other field is also stored or not),
Session Time, Session Start Time,
Session End Time, Session Expire
Time. I dont know what all things
are usually taken.
Do I need to encrypt Session Id
before storing into database. If Yes
Encryption will be automatic or do i need to write some code to do this other than that I wrote in web config above.
How mode='custom' will be used into
web config using my database.
in following code
<sessionState mode="Custom" cookieless="AutoDetect" timeout="15" regenerateExpiredSessionId="true" stateNetworkTimeout="10" >
</sessionState>
If you're using the SQL Server session provider, you should run aspnet_regsql to create the tables you need:
aspnet_regsql –E -S localhost –ssadd –sstype p
(replace localhost with .\SQLEXPRESS if you're using SQL Express)
You can also specify a custom DB name with the -d flag if you don't want the command to create the aspnetdb database. You can also run the command without flags to use wizard mode.
If you want to build a custom session provider (not a small task), you might start by looking at the script that's run by the command above:
C:\Windows\Microsoft.NET\Framework\v2.0.50727\InstallPersistSqlState.sql
Although it depends on your requirements, generally encryption of session state doesn't add much value. However, if your data is particularly sensitive, then it might be worth considering. Note, though, that the biggest risk with session state normally isn't on the DB side, rather it's on the client side, with one user being able to steal a session from another user, by getting access to their session cookie. Because of that, before I resorted to encrypting on the DB side, I would at least use SSL for all pages that reference the session cookie.
In case it helps, I cover many aspects of customizing session state in my book, although I stop short of demonstrating a full custom provider: Ultra-Fast ASP.NET.
Question set 1:
Depends on how you implement your provider. MSDN will tell you how to do that.
I would say no, but I'm not a security expert.
Set 2:
What do you mean?

Resources