This section discusses some important points that one should
keep in mind when working with Session State in ASP.NET. I have put together
some of the most important points here.
1.
We should be well aware of the amount of the data that we store in the
Session, particularly for sites that have a heavy traffic. In a distributed
web server environment, the use of Session variables can degrade performance.
2.
The Session IDs are stored in the Cookies in the Client side and are
used for communication between the Server and the Client. If the Session does
not contain a Cookie, the Session ID is maintained using the URL only.
3.
It should be noted that the SessionID lasts as long as the user’s session
of communication with the web server is active, i.e., as long as the browser
instance is unchanged. This can happen even after expiry of the Session after
the specified timeout period. Note that if the application has never stored
anything in the session state, a new session state with a new Session ID is
created with every request. In SQLServer mode of Session State storage, the session
expiration is carried out by the SQL Agent using a registered job.
4.
The Session timeout value is specified web.config file. It is a sliding
expiration value and indicates the time (in minutes) that the Session can be
idle before it is abandoned. When a session times out, the session data is
flushed out, the Session object is killed and a new one is created on a subsequent
hit to the page. The Session timeout value is a sliding expiration value.
5.
Note that the Session state is available only after the
HttpApplication.AcquireRequestState event is called. The Session_End event is supported
only in the InProc mode and is fired internally by the Web Server, based on an
internal timer. Thus, there is no HttpRequest that is associated when that
happens. This is why the methods Response.Redirect or Server.Transfer do not
work in the Session_End event. The Session_OnEnd event is called when we make
a call to the Session.Abandon method or when the Session times out.
6.
Storing the basic types in the Session state is much faster compared to storing
object types due to the serialization and de-serialization overhead involved.
7.
The IsNewSession property of the HttpSessionState class can be used to
detect whether a Session has timed out or was abandoned.
8.
Remember never to use a Response.Redirect or Server.Transfer method call
after you set the Session in the login page of your application. Both these
methods call the Response.End method internally. The Session ID would be lost
as the Response.End method stops execution of the page. Use the FormsAuthentication.RedirectFromLoginPage
method instead. Alternatively, you can use the following overloaded version of
the Response.Redirect method.
9.
Response.Redirect("~/menu.aspx", false)
10. This
would not abort the current thread and would prevent the Session ID from being
lost.