Search code examples
asp.netsession-state

ASP.NET Life cycle. Saving Session to database


I have an ASP.NET application that is using the SQLServer Session mode. I Created the below property in my page.

internal List<string> TargetTypes
{
    get { return Session["TargetTypes"] != null ? Session["TargetTypes"] as List<string> : null; }
    set { Session["TargetTypes"] = value; }
}

Later in the page I access this property in order to add values to it as shown below

TargetTypes.Add("Value1");
TargetTypes.Add("Value2");
TargetTypes.Add("Value3");

My concern is that how the Session is managed. Does the ASP read/write to the database each time I access this property? Or is there an event that is used to save all the sessions to database?


Solution

  • how the Session is managed?

    When Browser send request to your website then server generates a UID called sessionid and this 'Sessionid' is managed in Session Table. A table is created on the server for managing the session id for various web clients( Browsers). This session id is sent to the client. after this session is also sent to the server after first request.

    There two modes InProc and OutProc(Sql server, stateserver etc). Check these links for more information:
    Session State Management in Asp.net
    Session State

    When you set the <sessionState mode="SQLServer" then it saves the session values to the sql database. Follow this link to know how SessionState Works under StateServer mode.
    Fast, Scalable, and Secure Session State Management for Your Web Applications

    Does the ASP read/write to the database each time I access this property?

    Session state is managed by the SessionStateModule class, which calls the session-state store provider to read and write session data to the data store at different times during a request. At the beginning of a request, the SessionStateModule instance retrieves data from the data source by calling the GetItemExclusive method, or if the EnableSessionState page attribute has been set to ReadOnly, by calling the GetItem method. At the end of a request, if the session-state values have been modified, the SessionStateModule instance calls the SessionStateStoreProviderBase.SetAndReleaseItemExclusive method to write the updated values to the session-state store. Follow this for more details and Check SessionState Overview for your both second and third question clarification.

    Regarding your code snippet: When session start first time then all values will be null so you must check for session that is it new Session?? as you doing in Getter.