Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4: How to maintain sessions and cookies to be still valid after IIS restart?

It seems that my login session (using simple membership) and cookies (verification token) are not valid after IIS server restart. This is a problem for me, if a user in the middle of a transaction then the server restart, the user has to refill the form and do it again, also it can be some code issue when the transaction is interrupted in the middle of the process.

How to make them to be still valid after server restart?

Here is my web.config:

<membership />
...
<sessionState mode="InProc" cookieless="false" timeout="2880" />
...
<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication> 
...
<staticContent>
  <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
  <remove fileExtension=".woff" />
  <remove fileExtension=".woff2" />
  <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
  <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
</staticContent>

Update

I tried to use SQLServer to store the session state. Then new problem arise, which I cannot use ViewBag because it is not Serializable.

Is there another way I can achieve this?

like image 960
Alvin Stefanus Avatar asked Feb 07 '17 08:02

Alvin Stefanus


3 Answers

There is no way to achieve this AFAIK. You can always use Database or File to keep session and cookie values.

Idea could be you serialize the object that you want to keep in Session or Cookie. There are many tools that does serialization for you, I use newtonsoft. Then store it as string in DB along with session key.

For getting it back you can simply fire a query based on session key, get string and deserialize it and you are done :)

like image 191
Imad Avatar answered Oct 16 '22 05:10

Imad


By default, Session data is store in memory. Hence, you lost it when IIS restarts. You may consider other out of proc sessionstate provider to store the data, e.g. database, sessionstate service.

like image 21
mattfei Avatar answered Oct 16 '22 04:10

mattfei


Cookies are stored in the clients browser and sent on every request to the server. Therefore cookies are available across IIS restarts or AppDomain recyles.

Session data is by default not kept across AppDomain recycle or IIS restart. The only way to achieve this is to use a session state provider like the one for SQL server.

For this to work the session state provider needs to be able to serialize/deserilize your data in order to persist and restore it from the database, this means that you need to use types which is serializeable in your session.

You could change your code to use other types which are serializeable or store your data in a cookie instead.

like image 30
Oskar Sjöberg Avatar answered Oct 16 '22 03:10

Oskar Sjöberg