Understanding ASP.Net session life time

2020-02-26 13:24发布

问题:

I am confused about ASP or ASP.Net session life time (or life cycle) concepts. More specifically, my confusions are:

  1. How does IIS decide when a new session starts and an existing session ends? Especially how does IIS decide whether a session continues or ends when we call redirect code?
  2. How can we set session expire time? (Currently I only know to set it through web.config sessionState item.)
  3. Is it possible for one session to access another session's variables?

回答1:

  1. Session starts because the request does not contain a session cookie or the session cookie it does contain no longer maps to a session. A session ends by a) it has sat idle with no further requests referencing it for the timeout period. b) Its deliberately aborted by code. c) In-process session dies when the process does, e.g. when the app is recycled.

  2. Different ways to change the timeout are basically modifing the web.config anyway or a config file from which the value is inherited.

  3. Not unless the session object is deliberately placed by code somewhere that another session can access it.



回答2:

Session is generally handled by generating a unique identifier as a cookie on the clients machine. This is usually a session cookie, so you can't easily get to it. When you visit a site that uses sessions, it looks for this cookie. If it doesn't find it, it creates a new one, thus creating a new session.

One way to set the expire time is in the web.config, you can also set it in IIS by going to your website properties -> Home directory tab ->Configuration button -> Options Tab -> Session Timeout.

You will not be able to access someone elses session data.



回答3:

You can set session timeout programatically with:

Session.Timeout = 60; 


回答4:

Don't forget the AppPool settings too...by default (IIS 6 anyway) it will recycle every 120 minutes. So it's possible that someone could lose their session in less than the set Session_Timeout value.