What can destroy a session object asp .net? - c#

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

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)

what is process dependency in asp session state

I read from MSDN site that ASP session state is process dependent and the actions that affect the process also affect session state, where as ASP.Net session state is process independent. Also I have read that since ASP.Net follows out-of-process model it supports server farm configurations.
I tried to search and figure out what they mean by process but out of luck
What is exactly meant by Process in that definition?
An example would be helpful for me to understand it better
That means if you are using InProc session state then it will be dependent on your apppool. If apppool resets you will loose session. So, to avoid this you can use State server or Sql server mode of session state.
In a server farm configuration, you have multiple machines serving the single website. When you use InProc sessions in a server farm, then every server has it's own independent Session state.
When you use stateserver or sqlserver as session store, then session state is stored in a separate server, outside of the webserver process. This store is accessed by all webservers, which means they share the session state.

ASP.NET MVC Cache is clearing itself

I have a ASP.NET MVC 4 application which is running on a Windows 2012 R2 with IIS 8.5 machine. There is a wierd behavior which I cannot figure it out. The cache seems is clearing itself. By cache, I mean MemoryCache.Default, HttpContext.Current.Cache, and also OutputCache. I'm googling the issue for hours and seems nothing is wrong. Can you list cause of clearing cache? I mean is there a checklist which I can test the server against it? Thanks in advance.
Those caches are held in memory, and as such are volatile. They are held against the W3wp process that IIS spawns to handle those requests.
After a period of inactivity, IIS closes down the processes, so these caches will be cleared.
IIS also closes down the processes (recycles the app pool)
By default after 1746 mins (IIRC)
After the memory used by a thread reaches a set threshold
Caches are also isolated by thread, so if you have a web farm/web garden, these caches are not shared, again IIRC
If you need to persist these items longer, then you will need to look at caching the objects in a persisted storage area, such as a db or application state managed server.

Sessionstate not being saved between pages

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.

ASP.NET Session size limitation

Is there some kind of Session size limitation or advisable value to not to surpass ?
In my web application I create a few DataTables to store user selections which are stored in session until user approves selections so I add those values to database.
The problem is that I don't know whether session is reliable enough to keep few objects in or not ?
Thanks!
more info
Session size is about 10-20KB max.
Here's a few notes about Session state:
InProc (mode="InProc") session state is limited to the amount of memory available to the worker process. Only object references are stored, not the objects themselves.
Out of process state management serialises objects before persisting them:
Out of Process state management using the session state server (mode="StateServer") is limited to the amount of memory available to the state service.
Out of Process state management using SQL Server (mode="SQLServer") is bound only by the maximum size of the SQL image data type or the maximum permitted size of the database.
Obviously there still has to be enough memory available to the worker process to be able to pull an out of session object back into memory and re-hydrate for the duration of the http request.
As I mentioned previously, out of process state management serialises objects before persisting them.
This means that objects must be serialisable which excludes, for example, XmlDocument or anything that inherits from MarshalByRef.
Attempting to serialise objects of this sort will result in the following exception:
Unable to serialize the session state. In 'StateServer' and
'SQLServer' mode, ASP.NET will serialize the session state objects,
and as a result non-serializable objects or MarshalByRef objects are
not permitted. The same restriction applies if similar serialization
is done by the custom session state store in 'Custom' mode.
Yes, it is reliable enough. It just isn't very scalable, so plan ahead. This will totally grind to a halt when you run it on more than 1 server.
And there is sort of a limit: Number-of-concurrent-Users * SizeOf-Session < Available-Mem
It depends of course on the size of the tables, storing a few kB is usually acceptable (although high traffic sites will try to keep it smaller).
If your users can share tables, then you can place that data in the Application object, a great saving.
And a session object is limited to the TimeOut setting, default is 20 min. One way to optimize memory consumption is reducing that, but that is a trade off with user convenience.
I am assuming that you are having the session stored in "inProc" mode. In this mode, ASP.NET applications' session, cache etc are stored in the web server's RAM (via aspnet_wp.exe process). And .NET does not get to use all of it. There is a setting in machine.config which tells the threshold limit (by default 60%). Once this threshold is reached, IIS will recycle the worker process, and all the session information is lost.
Note that, if your server hosts more than one asp.net application, the 60% of memory is to be shared by all apps. So if the cumulative memory usage reaches the threshold the worker process still gets recycled.
Alternative to this, besides optimizing your application to use session sparingly,is to set the application to use session in out of process mode (using a stateserver or sqlserver to store session information).
Out of process mode can bring down your system performance.
Refer to this article for more information on Session State Management.
You should always assume session is a very valuable storage and very limited. The consumption should be as little as possible, because you can never know how many users the application is going to support.
DataTable can be too large to store in sessions, unless it can be kept small enough.

Categories

Resources