Sessionstate not being saved between pages - c#

i am having problems with an asp.net c# site whereby i am setting a session state object to true and then redirecting to another page that needs to check the value of the session state object and it is null.
Sometimes it is set correctly and other times is is simply null.
When i debug on my local machine it works perfectly every time. Only when i upload to my web server does this temperamental behaviour happen.
As it is based around the security of the site it is obviously important that the session data be valid and accurate every time.
Is session state data unreliable?
AFAIK its set to inproc, cookieless, 30 min timeout, vanilla installation of IIS.
Does anyone have any suggestions? Perhaps i need to thread.sleep inbetween the storing of the session data and the reading?
NB: the time between the write and the read is about 70ms.. ample time for the data to be written to RAM.....

No. It sounds like you are misusing session state. You can not rely on the user's session to be there. Your ASP.NET worker process could recycle, restarting the application and killing all sessions, or a file could change in your website, causing your application to restart and flushing all sessions, cookies could get flushed on the client, timeouts could happen, etc.
So you have to provide for all of these scenarios with Session State. Try to avoid using session state for things like this. If you're setting access inside your session state and you don't know exactly how it works, you could be opening your site up for a lot of security risks.

Everything point to a web farm. If you have different web servers on the production environment serving your application you would experiment this behavior.
I don't find any other explanation for this "WORKS ON MY MACHINE!"

I don't have an answer for your particular problem, but Claudio my be on to something.
What I have to say is that using session for security is so 90's. Literally.
FormsAuthentication was developed to replace that technique and does quite a fine job.
You should only rely upon session for trivial concerns that are easily recoverable.
Security is not one of those.

If the session state is lost, typically that's because your process either recycles or fails. I would never "rely" on the session state between pages. Instead you might want to try to persist data between pages some other way. Perhaps passing the information via form variables or saving the data in the database.
ASP.NET Profiles are a preferred way to save this sort of information. You might want to read ASP.NET State Management Recommendations.

Related

Is it possible to Serialize/Deserialize Session object in asp.net

I have the following session configuration in web.config
<sessionState mode="InProc" timeout="1440" cookieless="false">
However for some reason session is timing out. So all I want to do is if the session is expired then reload the saved session, if session serialization is possbile. Is it possible to save a Session object then reload it?
Johnny5's comment probably hit the nail on the head--your process will shut down after a period of inactivity and all InProc sessions will be lost. I don't think IISExpress under Visual Studio gives you a way to control this, so consider running under full-blown IIS during development and increase your app pool's "idle timeout" property to 1440.
But if you really are looking for a way to save a session, the Session_Start and Session_End events in Global.asax are one place to do this. HttpSessionState isn't serializable, so you'd need to either use a different serializer (as Ernesto suggested) or extract all of the session entries and put them into a different type of serializable collection. (The HttpApplication.Session property is read-only, so it'll probably be easiest to take the latter approach in any case since you can't just swap out full session instances..)
But be warned: you'll have problems with Session_End if you're using InProc--it's much too flaky for all but the most trivial uses. App pools regularly recycle themselves for any number of reasons (predefined intervals, high memory usage, inactivity, etc...) and you won't get the nice Session_End event prior to restart, so you'll lose your sessions without them being persisted.
That's why everyone tells you to use an out-of-process provider if you care the least bit about your sessions. The SQL Server and StateServer modes that ship with ASP.NET are the obvious choices, but if you're looking to do long term storage then you may run into a problem because they don't fire the Session_End event.
My employer (ScaleOut Software) has one of the rare out-of-process session providers that can fire Session_End. It's a commercial product, but it can be run for free on a single server if you only have basic needs and don't require all the scalability and fault tolerance that ScaleOut SessionServer can provide.
Just increase the session timeout property. If you want more fine grained control of the Session itself, you can change the sessionState mode to use a state server or SQL server (https://msdn.microsoft.com/en-us/library/ms178586.aspx)

Losing session after file changed / uploaded

I am currently having a strange issue with sessions, I've worked with MVC for quite a while and never had this in previous versions. Currently making a new system using MVC5 for the first time, all is well. Sessions are being set with no issues, however, if I modify a cshtml file in VS my session is killed.
Also I have a file upload feature which works, but when you upload a file and then navigate to another page the session is gone again. This is working locally and also on a Windows Server box we use for sandboxing.
Has something changed with the new versions of MVC regarding sessions? I've never had this before. I've got it set to use in-proc sessions, never normally needed to change anything but I have for the sake of things used cookieless, used cookies etc as options. Nothing seems to work.
If anyone has an idea that would be great.
It is interesting that you haven't observed this earlier - as always when you update the contents of your web site, IIS could recompile declarative resources causing the restart of the app pool which effectively removes all session data stored in memory.
A solution would be to switch to other, persistent session storages, sql is possibly the easiest to configure. You just need a sql server where you run the script that creates the session database:
http://support.microsoft.com/kb/317604
Another option would be to use the State Server:
http://msdn.microsoft.com/en-us/library/ms178586.aspx
The performance of the State Server is usually better than the SQl Server as the data is not persisted onto the disk. However, since the state server is a separate process, your application server won't loose sessions even when the app pool restarts.

What can destroy a session object asp .net?

I work with Session[""] objects in ASP .NET/C# MVC. I do a lot of checking on them, but I ask myself, what can destroy a session object without I specify it ?
I want to be sure that these Session[""] will be intact during some processes and can be only cleared by my instructions or if the user quit the application.
If you're using InProc, then a number of things can kill a sessions state. e.g.
Timeout (this can be set in config)
AppPool recycle
Web.Config change
Server crash
If you need a more durable solution, have a read of this article, and there's a few alternatives in this article too.
It's dependent on the type of session state you use.
InProc - sessions are destroyed if the web server process shuts down or crashes. The default shutdown time is 20 minutes after the IIS Application Pool is in active. If the IIS Application pool hits its memory limits it will also shutdown, so this is the least recommended approach for session state management.
StateServer - sessions are stored in a separate service on a server. The session will stay active until this service shuts down or is unavailable. It's more reliable than InProc, but if the service shuts down you loose any session data.
SQLServer - sessions are stored in a SQL database. This is the most robust solution and sessions are essentially guaranteed until you destroy them, but it's also the most complex to set up, requiring SQL server and a database.
Custom - Some other method of storing sessions that you would have to specify.
More information on the subject can be found in the links below.
http://msdn.microsoft.com/en-us/library/vstudio/ms178581%28v=vs.100%29.aspx
http://msdn.microsoft.com/en-us/library/vstudio/system.web.sessionstate.sessionstatemode%28v=vs.100%29.aspx

Session State Server vs Custom Session State Provider

I have been tasked to scale out the session for an application. From my research the most obvious choice is to use the State Server session provider, because I don't need the users sessions to persist (SQL Server Session provider)
About the app:
Currently using InProc session provider
All objects stored in session are serializable
All objects are small (mostly simple objects (int, string) and a few simple class instances)
Before I dive head-first into the IT side of things and with the ability to provide a custom session provider with ASP.NET 4, should I even consider a custom session state provider. Why or why not? Are there any "good" ones out there?
Thanks!
User feedback:
Why are we using session: persistence of data between postbacks (e.g. user selections)
How: user makes a selection, selection is stored. User leaves a page and returns,
selections are restored. etc. etc.
Will be creating a web farm
I've provided some links you can read up on on properly scaling session using the state server.
Useful links from Maarten Balliauw's blog:
http://blog.maartenballiauw.be/post/2007/11/ASPNET-load-balancing-and-ASPNET-state-server-%28aspnet_state%29.aspx
http://blog.maartenballiauw.be/post/2008/01/ASPNET-Session-State-Partitioning.aspx
http://blog.maartenballiauw.be/post/2008/01/ASPNET-Session-State-Partitioning-using-State-Server-Load-Balancing.aspx
My State Server related projects:
http://www.codeproject.com/KB/aspnet/p2pstateserver.aspx (latest code at https://github.com/tenor/p2pStateServer)
http://www.codeproject.com/KB/aspnet/stateserverfailover.aspx
Hope that helps.
It depends on what you mean by "scaling" session storage. If your simply talking about session state performance, your not going to beat the in-process session state provider. Switching to the State Server provider will actually make things slower -- due to the extra overhead of serializing and transferring objects across process boundaries.
Where the State Server can help you scale, is that it allows multiple machines in a load balanced web-farm to share a single session state. It is limited by machine memory, however, and if you will have lots of concurrent sessions you may want to use the SQL Session State provider.
For the most performance in a web farm, you can also try using AppFabric as was previously suggested. I haven't done it myself but it is explained here.
Also, here's a link for using Memcached as a Session State provider. Again, I haven't used it, so I can't offer an opinion on it...
EDIT: As #HOCA mentions in the comments, there are 3rd party solutions if cost isn't an issue. One I've heard of (but not used) is ScaleOut SessionServer.
I would highly recommend that before you look in to scaling out session that you first evaluate whether session was even needed in the first place.
Session variables are serialized and deserialized for every single page load whether the page uses that data or not. (EDIT: Craig pointed out that you have some level of control over this in .net 4 http://msdn.microsoft.com/en-us/library/system.web.sessionstate.sessionstatebehavior.aspx However, this still has drawbacks, see comments to this answer.)
For single server instances this is okay as you are just pulling it from the local memory of your web server. The load on these apps tend to be pretty small so caching user specific information locally makes sense.
However, as soon as you move storage of session to another server you have increased the network requirements and page load times of your application. Namely, every page will result in the session data to be moved from the remote server, across the network wire, and into memory of the web server.
At this point you have to ask yourself: is the load to pull this information from the database server directly as necessary more than pulling it from the session server every single time?
There are few instances where pulling it from the database server as needed takes longer or results in more traffic than grabbing it from a remote session server.
Bearing in mind that a lot of people set up their database server(s) to also be session servers and you start to see why use of session doesn't make any sense.
The only time I would consider using session for load balanced web apps is if the time to acquire the data exceeded a "reasonable" amount of time. For example, if you have a really complex query to return a single value and this query would have to be run for lots of pages. But even then there are better ways that reduce the complexity of dealing with remote session data.
I would advise against the use of session state, regardless of the provider.
Especially with your "very small objects" use viewstate. Why?
Scales best of all. NOTHING to remember on the server.
NO worries about session timeout.
No worries about webfarms.
No worries about wasted resources for sessions that will never come back.
Especially in ASP.NET 4 viewstate can be very manageable and small.

How to develop a web application that is load-balance friendly

Starting to develop to actual code to my website and wanted to know how do i develop or design the website that is load balance friendly. I read a post on stackoverflow regarding scalability and the selected answer stated: "Make sure you consider load balancing when developing your application". How do I go about this?
Your decision will come down to environment. If this is a product for sale, you will not have any control over the load balancing implementation. This means that "sticky sessions," where a user is bound to the same server for the duration of a session, cannot be guaranteed. Sticky sessions allow just about any application to be load-balanced, but they are not as efficient.
If you cannot guarantee an implementation with sticky sessions, avoid the usage of Session state altogether, or look into a shared-session solution.
1) do not use static fields to store data, statistics, ...
2) use session with care - you can still use in-process with sticky ssessions but I do not like it.
3) Do not rely on the IP of the server
Well, one answer is to reduce reliance upon session variables. It's possible to share session variables between servers via session server, but that means all your servers have a single point of failure on the session server then, plus reducing performance.
Basically, just try to make each page as stand-alone and stateless as possible, and you'll be good.
This might be obvious to most of you, but actually was an issue in our environment when we started to use a load balancer / several web servers: Do not rely on the IP addresses of your web server.
We had a production environment that used a switch and a set of internal IP addresses, including the one of the web server (our products usually run in a closed off environment, not the open Internet). If you have several web servers that becomes a problem.
Make sure you have a development/QA environment where you can test your software in a load balanced environment and see the issues in your code as you develop it rather than waiting until the deployment day.
One thing to take into account is the usage of Session data to maintain state.
As your application subsequent requests can be handled by other servers in the balance line you can not use InProc mode and StateServer mode.

Categories

Resources